我计划在我正在构建的框架中做“扩展点”,我正在寻找一种方法来为扩展提供“核心”,这样它就可以添加功能,但不会暴露核心对象,它可以被任意被操纵(我知道提供一个接口(interface)是更好的主意)但是,当我在测试(以及学习)时,我想知道为什么会这样:
(function() {
var core = {'bar': 'foo'}
function getCore() {return core;}
window.kit = {
core: core,
getCore: getCore
}
}());
//initial check
console.log(kit.core)
console.log(kit.getCore());
//change the bar
kit.core.bar = 'baz';
//we will both see 'baz'
console.log(kit.core)
console.log(kit.getCore());
//null the core
kit.core = null;
//this time...
console.log(kit.core) //core is null on this one
console.log(kit.getCore()); //why is the core still there on this one?
最佳答案
了解对象和对象引用之间的区别很重要。
一开始,core
和kit.core
引用同一个对象。对对象本身的任何更改都将反射(reflect)在对该对象的所有引用中。但是,如果其中一个引用发生更改,其他引用不会自动更改。
这一行:
kit.core.bar = 'baz';
修改kit.core
和core
引用的对象。引用不会改变,但对象会改变。这在两个引用文献中都有体现。
这一行:
kit.core = null;
将引用 kit.core
修改为引用 null
但不更改 core
,它仍然引用原始对象。对象本身不会改变。
关于javascript - 意外的关闭行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10080628/