我们可以在Javascript中修改不可变对象的方法吗?

时间:2015-10-04 18:07:52

标签: javascript methods immutability language-concepts

我对Javascript中的不变性概念感到疯狂。这个概念被解释为"在创建之后,它永远不会改变。" 但它究竟意味着什么?我理解了字符串内容的例子

 var statement = "I am an immutable value";
 var otherStr = statement.slice(8, 17);

第二行决不会改变语句中的字符串。 但是方法怎么样?你能举一个方法的不变性的例子吗?我希望你能帮助我,谢谢你。

1 个答案:

答案 0 :(得分:1)

字符串中的不变性有助于将字符串传递给函数,以便稍后使用(例如,在setTimeout中)。



var s = "I am immutable";

function capture(a) {
  setTimeout(function() { // set a timeout so this happens after the s is changed
    console.log("old value: " + a); // should have the old value: 'I am immutable'
  }, 2000);
}

capture(s); // send s to a function that sets a timeout.
s += "Am I really?"; // change it's value
console.log("new value: " + s); // s has the new value here




通过这种方式,您可以确定无论您对全局范围内的 s 所做的更改都不会影响捕获<范围内的(旧s)值/ strong>功能。

您可以在此plunker

中查看此信息