[英]How can I scope this “public” method correctly?
I have this code (JSFiddle) 我有这段代码(JSFiddle)
var OBJ = function(){
var privateVar = 23;
var self = this;
return {
thePrivateVar : function() {
return privateVar;
},
thePrivateVarTimeout : function() {
setTimeout(function() { alert(self.thePrivateVar()); } , 10);
}
}
}();
alert(OBJ.thePrivateVar());
OBJ.thePrivateVarTimeout();
This is an abstraction of a real problem I'm having. 这是我遇到的一个实际问题的抽象。
So - I would expect the call to OBJ.thePrivateVarTimeout()
to wait 10
and then alert
with 23 (which I want it to access through the other exposed method). 所以-我希望对
OBJ.thePrivateVarTimeout()
的调用要等待10
,然后用23发出alert
(我希望它可以通过其他公开的方法访问)。
However self
doesn't seem to be setting correctly. 但是,
self
似乎没有正确设置。 When I am setting self = this
it appears that this
isn't a reference to the function but a reference to the global object. 当我设置
self = this
看来this
不是一个参考功能,但对全局对象的引用。 Why is this? 为什么是这样?
How can I make the public method thePrivateVarTimeout
call the other public method thePrivateVar
? 如何使公共方法
thePrivateVarTimeout
调用另一个公共方法thePrivateVar
?
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
this === global || undefined
inside an invoked function. 在调用的函数中
this === global || undefined
。 In ES5 it's whatever the global environment is, in ES5 strict it is undefined. 在ES5中,无论全球环境如何,在ES5中严格来说它都是未定义的。
More common patterns would involve using the var that = this
as a local value in a function 更常见的模式将涉及使用
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;
}());
or using a .bindAll
method 或使用
.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.