「这个」对象创建期间的上下文
我正在尝试做这样的事情:
var test = {
a: 10,
b: 20,
c: (this.a+this.b)
};
但它不起作用。如何从 test.c 中访问 test.a? 是否可以?
I am trying to do something like this:
var test = {
a: 10,
b: 20,
c: (this.a+this.b)
};
but it doesn't work. How can I access the test.a from within test.c?
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可能在指定对象文字的表达式中引用“this”。要么在下面的行中执行此操作,要么使用如下所示的构造函数:
根据哪种方法更快,使用对象构造函数创建更快。这是一个简单的测试用例比较。 在 JSBIN 上自行运行。
结果表明,使用构造函数创建对象与使用对象字面量创建对象的速度几乎是对象创建速度的两倍:
这也是内联的测试代码:
It's not possible to reference "this" in an expression specifying an object literal. Either do it in a following line or use a constructor like this:
In response to which method is faster, creation with the object constructor is faster. Here's a simple test case comparison. Run it yourself on JSBIN.
The results show that the object creation with a constructor vs an object literal is almost twice as fast:
Here's the test code inlined as well:
在对象字面量中这是不可能的,因为
this
无法引用尚未创建的对象。最好的选择是在单独的步骤中分配c
属性:It's not possible within an object literal since
this
cannot be made to refer to an object that has not yet been created. Your best option is to assign thec
property in a separate step:在声明对象字面量时,您根本无法执行此操作,您可以做的最接近的是:
在您的上下文中
this
指的是您所在的任何父上下文,而不是test
对象...即使它确实如此,您也不能像这样声明成员,例如这也是无效的:...因为
test
、a
和 < code>b 尚未定义,因为它是尚未完成的单个语句。You simply can't do this when declaring an object literal, the closest you can do is:
In your context
this
refers to whatever parent context you're in, not thetest
object...and even if it did, you can't declare members like that, for example this is also invalid:...because
test
,a
andb
aren't defined yet, since it's a single statement that hasn't completed.为什么不让 ca 函数始终返回 a+b 的当前值?
Why not make c a function so that it always returns the current value of a+b?