【发布时间】:2018-04-07 02:12:45
【问题描述】:
在 JavaScript 中创建对象时,this 似乎没有指向我正在创建的对象。
在下面的示例中,anArrayValue 应该是 "a",但它被记录为 undefined。
const anArray = ['a', 'b', 'c'];
const anObject = {
arrayIndex: 0,
// I want to use anObject.arrayIndex here, but it's undefined
anArrayValue: anArray[this.arrayIndex],
log() {
console.log(this.anArrayValue);
}
};
//logs undefined
anObject.log();
//logs 'a'
console.log(anArray[anObject.arrayIndex]);
【问题讨论】:
-
this 总是指向执行上下文的调用。这是一个在窗口上下文中执行声明的文字对象。因此 this.arrayIndex 正在调用 window.arrayIndex。你需要一个真实的对象来作为这种参考。
标签: javascript arrays object scope