var OBJ = (function(){
var privateVar = 23;
var self = {
thePrivateVar : function() {
return privateVar;
},
thePrivateVarTimeout : function() {
setTimeout(function() { alert(self.thePrivateVar); } , 10);
}
};
return self;
}());
this === global || undefined
在调用的函数内。在 ES5 中,无论全局环境是什么,在 ES5 严格中它是未定义的。
更常见的模式将涉及将var that = this
用作函数中的局部值
var obj = (function() {
var obj = {
property: "foobar",
timeout: function _timeout() {
var that = this;
setTimeout(alertData, 10);
function alertData() {
alert(that.property);
}
}
}
return obj;
}());
或使用.bindAll
方法
var obj = (function() {
var obj = {
alertData: function _alertData() {
alert(this.property);
}
property: "foobar",
timeout: function _timeout() {
setTimeout(this.alertData, 10);
}
}
bindAll(obj)
return obj;
}());
/*
bindAll binds all methods to have their context set to the object
@param Object obj - the object to bind methods on
@param Array methods - optional whitelist of methods to bind
@return Object - the bound object
*/
function bindAll(obj, whitelist) {
var keys = Object.keys(obj).filter(stripNonMethods);
(whitelist || keys).forEach(bindMethod);
function stripNonMethods(name) {
return typeof obj[name] === "function";
}
function bindMethod(name) {
obj[name] = obj[name].bind(obj);
}
return obj;
}