简体   繁体   English

在Javascript对象文字中使用属性

[英]Using properties inside a Javascript object literal

I'm looking to create javascript json object that has a dynamic field that will just return a value based on previously specified properties. 我正在寻找创建具有动态字段的javascript json对象,该字段将仅返回基于先前指定的属性的值。 So far This is what I have... 到目前为止这就是我所拥有的......

var car = {
  color: 'red',
  wheels: 4,
  hubcaps: 'spinning',
  age: 4,
  full_name: this.color + ' ' + this.spinning
}

I was wondering if this is possible to do? 我想知道这是否可行? My goal is to be able to reference values such as car.color or car.full_name . 我的目标是能够引用诸如car.colorcar.full_name值。 For this example car.full_name would return the value red spinning 对于此示例,car.full_name将返回red spinning

You can wrap your object in a function so you can perform operations on it, eg concatenations. 您可以将对象包装在函数中,以便对其执行操作,例如连接。

var car = function () {
    var color     = 'red',
        hubcaps   = 'spinning',
        full_name = color + ' ' + hubcaps;

    return {
       color: color,
       wheels: 4,
       hubcaps: hubcaps,
       age: 4,
       full_name: full_name
    };
// (); <- calls the anonymous function after defining it
}();

// true
car.full_name === "red spinning";

Edit: Like what @Jimmyt1988 said, if you want to instantiate new versions of this functions, ie OO Javascript, you can remove the inline function call (); 编辑:就像@ Jimmyt1988所说的那样,如果你想实例化这个函数的新版本,即OO Javascript,你可以删除内联函数调用(); and use it like so 并像这样使用它

var myCar = new car();

alert(mycar.color);

You cannot refer to other fields in the javascript literal when it is statically declared like you are doing because in the eyes of the parser, the object does not yet exist (it hasn't finished parsing) and it also doesn't set the this ptr like you are trying to use either. 当你正在静态声明它时,你不能引用javascript文字中的其他字段,因为在解析器的眼中,该对象尚不存在(它还没有完成解析)并且它也没有设置this ptr就像你正试图使用​​其中之一。

Instead, you would have to do this: 相反,你必须这样做:

var car = {
  color: 'red',
  wheels: 4,
  hubcaps: 'spinning',
  age: 4,
}

car.full_name = car.color + ' ' + car.spinning;

Your other option would be to turn full_name into either a function or a getter so that it is computed dynamically based on the other field values. 您的另一个选择是将full_name转换为函数或getter,以便根据其他字段值动态计算。

If you want full_name to always be dynamic, then you probably want to use a getter which can have a function behind it, but can be used like a property. 如果您希望full_name始终是动态的,那么您可能希望使用一个可以在其后面具有函数的getter ,但可以像属性一样使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM