我可以在JavaScript中的对象声明期间引用其他属性吗?

问题描述:

我正在尝试这样的事情:

I am trying to do something like this:

var obj = {
    a: 5,
    b: this.a + 1
}

(而不是5有一个函数,我不想执行两次返回一个数字)

(instead of 5 there is a function which I don't want to execute twice that returns a number)

我可以重写它以分配 obj.b 稍后从 obj.a ,但我可以在申报期间立即办理吗?

I can rewrite it to assign obj.b later from obj.a, but can I do it right away during declaration?

没有。 JavaScript中的这个不能像你想象的那样工作。 这个在这种情况下是指全局对象。

No. this in JavaScript does not work like you think it does. this in this case refers to the global object.

只有3个案例的值设置:

There are only 3 cases in which the value this gets set:

功能案例

foo();

这里这个将引用全球对象。

方法案例

test.foo(); 

在此示例中将引用 test 。

构造函数案例

new foo(); 

一个函数调用,前面是 new 关键字充当构造函数。在函数里面,这个将引用一个新的
创建的对象

A function call that's preceded by the new keyword acts as a constructor. Inside the function this will refer to a newly created Object.

其他地方,指的是全局对象。

Everywhere else, this refers to the global object.