对象文字中的引用变量? [英] reference variable in object literal?

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

问题描述

说我有

myfunc({
  var1: 1,
  var2: 2,
})

如果我想拥有一个利用当前未命名对象的值,我该怎么做?

if i want to have a value that makes use of the current unnamed object, how would I do this?

例如,如果我想要

myfunc({
  var1: 1,
  var2: 2,
  var3: this.var1 + this.var2
})

显然这不起作用。

正确的语法是什么?

推荐答案

不幸的是,这是不可能的。在构造对象文字时,在评估整个文字之前,不存在对该对象的外部引用。在此阶段使用的唯一方法是使用构造函数:

Unfortunately, that isn't possible. While an object literal is being constructed, no external reference to that object exists until the entire literal is evaluated. The only way to use this at this stage is to use a constructor instead:

function MyObject() {
  this.var1 = 1;
  this.var2 = 2;
  this.var3 = this.var1 + this.var2;
}

myfunc(new MyObject());

这篇关于对象文字中的引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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