我可以在JavaScript中的对象声明期间引用其他属性吗? [英] Can I reference other properties during object declaration in 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.
这篇关于我可以在JavaScript中的对象声明期间引用其他属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!