本文介绍了当前对象属性作为同一对象中的值不同的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这样一个随机的标题,但不知道如何更好地解释它。因此,不知道这是否是重复的问题。



所以,当声明一个新对象时,我正在计算 giga value:

  var myObject = {
super:1,
mega:5,
uber:100,
giga:this.super + this.mega + this.uber // super + mega + uber does not cut it .. ..
};

但是这不行,所以,在声明或者不可能的时候这样做的任何方法?



希望我提前明确表示感谢!

解决方案

p>在Javascript 1.5中,您可以使用 get 关键字来定义getter

  var obj = {
super:1,
mega:5,
uber:100,
get giga(){
return this.super + this。 mega + this.uber;
}
};

alert(obj.giga)// 106

a href =http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/ =noreferrer> http://robertnyman.com / 2009/05/28 / getters-and-setters-with-javascript-code-samples-and-demos /


Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.

So, when declaring a new object, I'm looking to calculate the giga value:

var myObject = {
    super : 1,
    mega : 5,
    uber : 100,
    giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};

But this doesn't work, so, any ways of doing this while declaring, or not possible?

Hope I've made myself clear and thanks in advance!

解决方案

In Javascript 1.5 you can use the get keyword to define a getter

var obj = {
    super : 1,
    mega : 5,
    uber : 100,
    get giga() {
        return this.super + this.mega + this.uber;
    }
};

alert(obj.giga) // 106

more on this http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

这篇关于当前对象属性作为同一对象中的值不同的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:06