我有以下对象。我试图从b
的回调中到达变量setTimeout
,但它不起作用。我知道setTimeout的回调只知道其周围函数的变量,那么我怎样才能到达this.b
?谢谢!
function someFunc() {
this.a = 10;
this.b = 20;
this.func = function() {
this.c = 50;
console.log("a = " + this.a); //works
var time = setTimeout(function() {
console.log("b = " + someFunc.b); //this.b doesn't work
console.log("C = " + this.c); //why this doesn't work also? says undefined
},1000);
}
}
var m = new someFunc();
m.func();
答案 0 :(得分:3)
function someFunc() {
this.a = 10;
this.b = 20;
var mySomeFunc = this;
this.func = function() {
console.log("a = " + this.a); //works
var time = setTimeout(function() {
console.log("b = " + mySomeFunc.b);
},1000);
}
}
答案 1 :(得分:2)
this
不引用函数对象;它指的是调用它的上下文。 (您的m
变量)
someFunc.b
是函数本身的属性(就像静态属性一样)
您需要在变量中保存对外部this
的引用。
答案 2 :(得分:0)
此外,您可以使用类似的内容在对象范围内执行匿名函数:
function createDelegate(instance, callback) {
return function () {
callback.apply(instance, arguments);
};
}
function someFunc() {
this.a = 10;
this.func = function() {
this.c = 50;
console.log("a = " + this.a);
var time = setTimeout(createDelegate(this, function() {
console.log("b = " + someFunc.b);
console.log("C = " + this.c);
}),1000);
}
}
someFunc.b = 20;
var m = new someFunc();
m.func();