我是JS的OOP新手。现在我试图在实例中调用变量,但是如何在函数中调用它?
var foo = function() {
this.a = 1; // how can I call 'a' in the setTimeout() function
this.start = function(i) {
if (i<3){
window.setTimeout(function() {
console.log(a); // this line shows undefined
console.log(this.a); // this line indicates 'this' is window
i++;
start(i); // this one does not work as well
}, 2000);
}
};
};
var bar = new foo();
bar.start(0);
答案 0 :(得分:0)
只需将this
存储在函数前的变量中:
var foo = function() {
this.a = 1; // how can I call 'a' in the setTimeout() function
this.start = function(i) {
var that = this;
if (i<3){
window.setTimeout(function() {
console.log(that.a);
i++;
that.start(i); // this one does not work as well
}, 2000);
}
};
};
var bar = new foo();
bar.start(0);
或者,您可以根据项目要求使用ES6的新arrow functions:
window.setTimeout(() => {
console.log(this.a);
i++;
this.start(i); // this one does not work as well
}, 2000);