我打算在一個框架即時通訊建設中做「擴展點」,並且我正在尋找一種方式,我可以如何爲擴展提供「核心」,以便它可以添加功能但不公開它的核心對象可以任意操縱(我知道提供的接口是更好的主意),但門檻,而我是測試(以及學習),我不知道爲什麼發生這種情況:意外的關閉行爲
(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?
另外注意'kit.core'不是一個引用或指針。這是一個值,就像本地變量'core'是一個值 – Raynos 2012-04-09 22:25:19
Raynos:'kit.core'指向'core'本地對象。如果你修改對象,另一個也會改變。 – 2012-04-09 22:29:34
@KarolyHorvath如果更改'kit.core'的**內容**,那麼「getCore()」函數將會看到更改。但是,如果你只是把'kit.core'指向新的東西,那麼(如OP所發現的),關係就會被破壞。 – Pointy 2012-04-09 22:30:54