我对 Javascript 中的不变性概念感到疯狂。这个概念被解释为“创建后,永远不会改变”。但这究竟是什么意思?我理解了字符串内容的示例
var statement = "I am an immutable value";
var otherStr = statement.slice(8, 17);
第二行绝不会更改statement中的字符串。但是方法呢?你能举一个方法不变性的例子吗?我希望你能帮助我,谢谢。
我对 Javascript 中的不变性概念感到疯狂。这个概念被解释为“创建后,永远不会改变”。但这究竟是什么意思?我理解了字符串内容的示例
var statement = "I am an immutable value";
var otherStr = statement.slice(8, 17);
第二行绝不会更改statement中的字符串。但是方法呢?你能举一个方法不变性的例子吗?我希望你能帮助我,谢谢。
将字符串传递给函数以便以后使用(例如,在 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进行什么更改,都不会影响捕获函数范围内的 a(旧 s)的值。
你可以在这个plunker中检查这个工作