对象文字/初始化器中的自引用 [英] Self-references in object literals / initializers

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

问题描述

有没有办法在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?

推荐答案

<嗯,我唯一可以告诉你的是吸气剂:

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

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

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天全站免登陆