对象字面量/初始值设定项中的自引用 [英] Self-references in object literals / initializers

查看:23
本文介绍了对象字面量/初始值设定项中的自引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以让类似下面的东西在 JavaScript 中工作吗?

Is there any way to get something like the following to work in JavaScript?

var foo = {
    a: 5,
    b: 6,
    c: this.a + this.b  // Doesn't work
};

在当前形式中,此代码显然会引发引用错误,因为this 不引用foo.但是有没有办法让对象字面量的属性中的值依赖于之前声明的其他属性?

In the current form, this code obviously throws a reference error since this doesn't refer to foo. But is there any way to have values in an object literal's properties depend on other properties declared earlier?

推荐答案

好吧,我唯一能告诉你的是 getter:

Well, the only thing that I can tell you about are getter:

var foo = {
  a: 5,
  b: 6,
  get c() {
    return this.a + this.b;
  }
}

console.log(foo.c) // 11

这是 ECMAScript 第 5 版规范引入的语法扩展,大多数现代浏览器(包括 IE9)都支持该语法.

This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).

这篇关于对象字面量/初始值设定项中的自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆