`this.prop` 在对象内部给出未定义?

`this.prop` giving undefined inside an object?

所以,我有这段代码:

const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
  something: this.prop,
};

console.log(test.func());
// expected output: 42, which we are getting. But...

console.log(test.something);
// expected output: 42, here the output is `undefined`.

我希望 something 成为同一对象的 prop 属性。函数 属性 返回值,但是当我记录 something 属性 时,它返回 undefined。 我在 node.jsbrowser 中也试过了。

为什么会发生这种情况,有人可以让它工作吗?

这可以使用 javascript 对象属性的 getter 和 setter 来实现。

例如你的情况:

const test = {
  prop: 42,
  get getProp() {
    return this.prop;
  },
};

您可以使用

获取道具的价值
test.getProp

这是调用上下文的问题:在 test.func() 中,this 上下文是 test 并且控制台 returns 正确 42。在 something 中,this 上下文是 window(不知道什么是 this.prop)和控制台 returns 未定义。那是因为:

In JavaScript the value of this not refer to the function in which it is used or it’s scope but is determined mostly by the invocation context of function (context.function()) and where it is called.

Source

你在第二个 console.log 中得到 undefined 的原因是因为 this 指的是 something 而不是对象 test.

这是由于调用上下文,在第一种情况下是测试,而在第二种情况下是某物。

调用上下文在.

之前确定