Jay*_*012 5 javascript closures
function modify(val, newVal) {
val = newVal;
}
constructorFunc = function () {
var _private = false;
return {
modifyPrivate: function(toVal) {
return modify(_private, toVal); // LINE REFERRED TO BELOW AS X
}
};
}
var x = constructorFunc();
x.modifyPrivate(true);
x.modifyPrivate(true); // _private still starts off as false, meaning it wasn't set to true
Run Code Online (Sandbox Code Playgroud)
我遇到的一个问题是为什么我第二次调用x.modifyPrivate(true)为什么在运行第X行时,传入的_private值仍为"false".
我可以理解这一点,如果我稍微修改我的闭包知识是通过引用完成闭包,并且当你更改引用的值时你没有查找原始引用所指向的值,那么你正在改变引用本身就指出了一些新的价值......但是这整个事情非常令人困惑,我相信那里的某个人可以指出我在网上的图解释了这一点.
我也非常有兴趣知道如何编写这段代码,以便事实上修改_private以便后续调用modify().
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |