过去几天我一直在努力解决这个问题,很高兴遇到这个问题。然而,经过一些实验,至少有一种情况似乎没有一个令人满意的答案:在公共函数和私有函数之间传递数据。
以下是三个示例,分别使用“调用”、“绑定”和普通调用。绑定似乎是将私有方法保持在本地范围内的唯一方法,并且还允许私有方法和公共方法之间的数据交换。将上下文传递给私有方法的另一个建议仍然会使私有方法在模块外部执行(如果我理解正确的话)。
有趣的是,使用普通调用(带/不带严格模式)允许数据交换,即使私有方法的上下文是“未定义”/“窗口”。
使用“绑定”:
"use strict";
var home = (function(){
var bob = function(){
console.log("Bob's scope: " + Object.keys(this)); // "Bob's scope: init"
var bob_says = "Hello";
var fBound = alice.bind(this);
var alice_reply = fBound(bob_says);
console.log("Alice answered: " + alice_reply); // "Alice answered: Hello Bob"
};
var alice = function(bob_greeting){
var scope = this ? Object.keys(this) : this;
console.log("Alice's scope: " + scope); // "Alice's scope: init"
console.log("Bob said: " + bob_greeting); // "Bob said: Hello"
return bob_greeting + " Bob";
};
return { init : bob };
})();
home.init();
使用“呼叫”:
"use strict";
var home = (function(){
var bob = function(){
console.log("Bob's scope: " + Object.keys(this)); // "Bob's scope: init"
var bob_says = "Hello";
var alice_reply = alice.call(this, bob_says);
console.log("Alice answered: " + alice_reply); // "Alice answered: undefined Bob"
};
var alice = function(self, bob_greeting){
var scope = this ? Object.keys(this) : this;
console.log("Alice's scope: " + scope); // "Alice's scope: init"
console.log("Bob said: " + bob_greeting); // "Bob said: undefined"
return bob_greeting + " Bob";
};
return { init : bob };
})();
home.init();
无需调用或绑定:
"use strict";
var home = (function(){
var bob = function(){
console.log("Bob's scope: " + Object.keys(this)); // "Bob's scope: init"
var bob_says = "Hello";
var alice_reply = alice(bob_says);
console.log("Alice answered: " + alice_reply); // "Alice answered: Hello Bob"
};
var alice = function(bob_greeting){
var scope = this ? Object.keys(this) : this;
console.log("Alice's scope: " + scope); // "Alice's scope: undefined"
console.log("Bob said: " + bob_greeting); // "Bob said: Hello"
return bob_greeting + " Bob";
};
return { init : bob };
})();
home.init();
更新和可能的答案。
我很好奇,当 Alice 在没有“调用”或“绑定”的情况下被调用,并且她的上下文未定义(或窗口)时,她是否可以访问“家”中的私有变量?是的,所以我对 OP(和我自己)的暂定答案是正常调用私有函数:没有'bind',没有'call',也不需要在上下文中传递,但是如果它困扰你,则“使用严格”查看运行私有函数时弹出的窗口上下文。似乎没有在“窗口”中创建新属性,并且如果窗口具有与私有函数同名的对象(无论严格模式是打开还是关闭),也不会发生冲突。如果有陷阱,我还没有遇到过。
"use strict";
var alice = "Hi, I'm global's Alice";
var home = (function(){
var bob = function(){
console.log("Bob's scope: " + Object.keys(this)); // "Bob's scope: init"
var bob_says = "Hello";
var alice_reply = alice(bob_says);
console.log("Alice answered: " + alice_reply); // "Alice answered: Hello Bob. I'm in the garage."
};
var alice_location = "in the garage.";
var alice = function(bob_greeting){
var scope = this ? Object.keys(this) : this;
console.log("Alice's scope: " + scope); // "Alice's scope: undefined"
console.log("Bob said: " + bob_greeting); // "Bob said: Hello"
return bob_greeting + " Bob. I'm " + alice_location;
};
return { init : bob };
})();
home.init();
console.log(alice);