首先,请参阅我的代码plz。
function test(){
this.item = 'string';
this.exec = function(){
something();
}
function something(){
console.log(this.item);
console.log('string');
}
}
然后我制作了类并调用“ exec函数”,就像这样的代码
var t = new test();
t.exec();
但是结果是...
undefined
string
我想从某种功能访问test.item。
你有什么解决办法吗?
您需要致电something
,apply
以便this
在内正确设置something
:
function test(){
this.item = 'string';
this.exec = function(){
something.apply(this);
}
function something(){
console.log(this.item);
console.log('string');
}
}
正如@aaronfay指出的,发生这种情况是因为this
没有引用new test()
创建的对象。您可以在此处了解更多信息,但一般规则是:
如果一个功能上的调用object
,然后this
指object
。如果一个函数是单独调用的(如代码中的情况),则this
引用全局对象,在浏览器中为window
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句