我有以下代码:
function A() {
this.value = 'a_value';
}
A.prototype.getValue = function(){
console.log(this.value); // got undefined, expected 'a_value'
}
setTimeout(new A().getValue, 100);
为什么我将this.value
定义为未定义。?
以及如何访问this.value
?
编辑:我不允许更改代码的setTimeout
行(最后一行)。
答案 0 :(得分:2)
提示:你试过console.log(this);
吗?
您只是将
getValue
函数传递给setTimeout
,而不是其上下文。这样的事情会起作用:setTimeout(function() {new A().getValue();},100);
但是如果不改变最后一行,你基本上什么也做不了。
答案 1 :(得分:1)
您可以完全避免使用this
,并且不会遇到以下技术的这类问题:
var A = function () { // no new no this
var value = 'a_value';
var getValue = function(){
console.log(value);
};
return Object.freeze({
getValue ,
});
};
setTimeout(A().getValue, 100);
或写
var a = new A();
之前,然后
setTimeout(a.getValue.bind(a), 100);