我有以下功能
var myInstance = (function() {
var privateVar = 'Test';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// all private members are accesible here
alert(privateVar);
},
publicMethod2: function () {
}
};
})();
Run Code Online (Sandbox Code Playgroud)
如果我在函数中添加新内容,会有什么不同.从萤火虫看来,似乎两个物体是相同的.据我了解,两者都应该强制执行单身模式.
var myInstance = new (function() {
var privateVar = 'Test';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// all private members are accesible here
alert(privateVar);
},
publicMethod2: function …Run Code Online (Sandbox Code Playgroud) 为什么立即调用的方法返回window对象this,
var o = {};
o.foo = function () {
console.log(this);
}(); //Window {…}
Run Code Online (Sandbox Code Playgroud)
但是当稍后执行时,该方法返回对象o(正如我在两种情况下都预期的那样)?
var o = {};
o.foo = function () {
console.log(this);
}
o.foo(); //Object {foo: function}
Run Code Online (Sandbox Code Playgroud)