this
指针直接在窗口中。 我的类对象指向该对象本身, 您正在使用它来定义该对象的本质属性, 如 n1 和 n2 。
然而,在您对象定义的函数范围内, this
指针指向函数,而不是对象。 *** 但是,在设置超时和设置 Intervals 中,“ this”关键字指向窗口对象或全球范围。 (见底端更新,例如。 )
因此,您可以直接访问属性, 使用您用来对类别进行即时处理的全局范围的变量名称,
this.returnAns = function(){
return myclassins.ans;
};
然而,上述方法将您的类与在即时时间给对象的命名联系起来,并且仅适用于单个对象。
更好的解决办法是定义对象内的变量,并引用“此”指针:
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.modifynumbers = (function(__this) {
return function(n1,n2){
__this.n1 = n1;
__this.n2 = n2;
}
})(this);
当然,最不复杂的方法是使用var self
;然而,在JavaScript,有几种不同的方法来完成一项任务,这些技术在不同的情景下可以证明是有用的。
UPDATE:
@apsillers指出,“此关键字”指向窗口对象时, 指向由设置Timeout 和设置 Interval 函数所引用的回调中引用的窗口对象。 以下是一个例子:
// 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();
< 强度 > 某些功能输出 () : 强度 >
# inside method of object
somevar = somevalue
global = undefined
# inside timeout
timeout - somevar = undefined
timeout - global = globalvalue
正如你可以看到的那样,在设定时间外,“这个”明确指向窗口或全球范围! (注:你可以拿下那个小代码片,然后在您的 Chrome 或 Firebug 调试器中运行。)