Javascript 对象如何引用自身的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2787245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:54:50  来源:igfitidea点击:

How can a Javascript object refer to values in itself?

javascriptobject

提问by Erin Drummond

Lets say I have the following javascript:

假设我有以下 javascript:

var obj = {
 key1 : "it ",
 key2 : key1 + " works!"
};
alert(obj.key2);

This errors with "key1 is not defined". I have tried

此错误与“key1 未定义”有关。我试过了

this.key1
this[key1]
obj.key1
obj[key1]
this["key1"]
obj["key1"]

and they never seem to be defined.

他们似乎从未被定义过。

How can I get key2 to refer to key1's value?

如何让 key2 引用 key1 的值?

采纳答案by pencilCake

Maybe you can think about removing the attribute to a function. I mean something like this:

也许您可以考虑删除函数的属性。我的意思是这样的:

var obj = {
  key1: "it ",
  key2: function() {
    return this.key1 + " works!";
  }
};

alert(obj.key2());

回答by user187291

This can be achieved by using constructor function instead of literal

这可以通过使用构造函数而不是文字来实现

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

回答by Tgr

You can't refer to a property of an object before you have initialized that object; use an external variable.

在初始化该对象之前,您不能引用该对象的属性;使用外部变量。

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

Also, this is not a "JSON object"; it is a Javascript object. JSON is a method of representing an object with a string (which happens to be valid Javascript code).

此外,这不是“JSON 对象”;它是一个 Javascript 对象。JSON 是一种用字符串(恰好是有效的 Javascript 代码)表示对象的方法。

回答by Edwin Dalorzo

One alternative would be to use a getter/setter methods.

一种替代方法是使用 getter/setter 方法。

For instance, if you only care about reading the calculated value:

例如,如果您只关心读取计算值:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

The above code, though, won't let you define another value for key2.

但是,上面的代码不会让您为 key2 定义另一个值。

So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.

因此,如果您还想重新定义 key2 的值​​,事情会变得更加复杂。它始终是一个计算值。很可能这就是你想要的。

However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.

但是,如果您希望能够重新定义 key2 的值​​,那么您将需要一个独立于计算的地方来缓存其值。

Somewhat like this:

有点像这样:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

Another interesting alternative is to use a self-initializing object:

另一个有趣的选择是使用自初始化对象:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

回答by Delan Azabani

Because the statement defining objhasn't finished, key1doesn't exist yet. Consider this solution:

因为语句定义obj还没有完成,key1还不存在。考虑这个解决方案:

var obj = { key1: "it" };
obj.key2 = obj.key1 + ' ' + 'works!';
// obj.key2 is now 'it works!'

回答by T.J. Crowder

That's not a JSONobject, that's a Javascript object created via object literal notation. (JSON is a textual notationfor data exchange (more). If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.)

那不是JSON对象,而是通过对象文字表示法创建的 Javascript 对象。(JSON 是用于数据交换的文本符号(更多)。如果您正在处理 JavaScript 源代码,而不是处理字符串,那么您就不是在处理 JSON。)

There's no way within the object initializer to refer to another key of the object being initialized, because there's no way to get a reference to the object being created until the initializer is finished. (There's no keyword akin to thisor something for this situation.)

在对象初始值设定项中无法引用正在初始化的对象的另一个键,因为在初始值设定项完成之前无法获得对正在创建的对象的引用。(this对于这种情况,没有类似于或类似的关键字。)

回答by Jason

You can also reference the objonce you are inside the function instead of this.

您还obj可以在进入函数后引用 ,而不是this.

var obj = {
    key1: "it",
    key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());

回答by Thomas

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

这不是JSON。JSON 被设计得非常简单;允许任意表达式并不简单。

In full JavaScript, I don't think you can do this directly. You cannot refer to thisuntil the object called objis fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

在完整的 JavaScript 中,我认为您不能直接执行此操作。thisobj完全构造被调用的对象之前,您不能引用。所以你需要一个解决方法,一个比我提供更多 JavaScript 功能的人。