直接位于 window.myclass 对象内部的this
指针指向该对象本身,您使用它来定义该对象的本质属性,例如 n1 和 n2。
但是,在对象中定义的函数中,this
指针指向的是函数,而不是对象。***然而,在 setTimeouts 和 setIntervals 中,“this”关键字指的是窗口对象或全局范围。(例如,请参阅底部的更新。)
因此,您可以使用用于实例化类的全局范围内的变量名称直接访问属性,
this.returnAns = function(){
return myclassins.ans;
};
但是,上述方法将您的类与实例化时赋予对象的名称相关联,并且仅对单个对象有用。
更好的解决方案是在对象中定义一个变量并使用它引用“this”指针:
window.myclass = function(){
this.n1 = 0;
this.n2 = 0;
this.ans = 0;
this.hehe = 0;
var _self = this; // reference to "this"
this.defaultNumbersAdd = function(){
myclass.hehe =setInterval(function(){
//just an example of inert function...
//the truth is i can't grab the this.n1 and this.n2...
_self.ans = _self.n1 + _self.n2;
console.log(_self.ans);
},100);
clearTimeout(_self.hehe);
};
this.returnAns = function(){
return _self.ans;
};
this.getAnswer = function(){
this.defaultNumbersAdd(); //i want to reuse this function but I can't access it
return _self.returnAns(); //and also this one
};
this.modifynumbers = function(n1,n2){
_self.n1 = n1;
_self.n2 = n2;
};
};
最后,另一种技术是使用闭包定义函数,将“this”指针传递给返回另一个函数的函数,如下所示:
this.modifynumbers = (function(__this) {
return function(n1,n2){
__this.n1 = n1;
__this.n2 = n2;
}
})(this);
当然,最简单的方法是使用var self
; 然而,在 JavaScript 中有几种不同的方式来完成一项任务,这些技术在不同的场景中可以证明是很方便的。
更新:
@apsillers 指出,当在 setTimeout 和 setInterval 函数调用的回调中引用时,“this”关键字指向窗口对象。这是一个例子:
// top level scope
var global = "globalvalue";
window.demo = function() {
this.somevar = "somevalue";
this.someFunct = function() {
console.info("somevar = " + this.somevar); // prints "somevalue"
console.info("global = " + this.global); // prints undefined! this points to "demo"!
setTimeout( function() {
console.info("timeout - somevar = " + this.somevar); // undefined! references the "window" context
console.info("timeout - global = " + this.global); // prints "globalvalue"
},1000);
};
};
var dem = new demo();
dem.somevar; // accessible from outside the object. prints "somevalue"
dem.someFunct();
someFunct() 的输出:
# inside method of object
somevar = somevalue
global = undefined
# inside timeout
timeout - somevar = undefined
timeout - global = globalvalue
如您所见,在 setTimeout 内部,“this”明确指向窗口或全局范围!(注意:您实际上可以获取那个小代码片段并在您的 Chrome 或 Firebug 调试器中运行它。)