首先,请参阅我的代码plz.
function test(){
this.item = 'string';
this.exec = function(){
something();
}
function something(){
console.log(this.item);
console.log('string');
}
}
Run Code Online (Sandbox Code Playgroud)
我做了类并调用'exec函数',就像这段代码一样
var t = new test();
t.exec();
Run Code Online (Sandbox Code Playgroud)
但结果是......
undefined
string
Run Code Online (Sandbox Code Playgroud)
我想从一些函数访问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');
}
}
Run Code Online (Sandbox Code Playgroud)
正如@aaronfay指出的那样,这是因为this没有引用new test()创建的对象.你可以在这里阅读更多相关信息,但一般规则是:
如果一个功能上的调用object,然后this指object.如果函数自己调用(如代码中的情况),则this引用浏览器中的全局对象window.