简体   繁体   English

将对象属性设置为同一对象中属性的负值(Javascript / jQuery)

[英]Set an object property to the negative value of a property in the same object (Javascript/jQuery)

Lets say I have a Javascript object: 可以说我有一个Javascript对象:

var myObj = {
 property1 : 20,
 property2 : -20
}

But instead of -20 for property2 , I need to take the value of property1 and convert it to its negative within property2 : 但不是-20property2 ,我需要的价值property1和其内转换成其消极property2

var myObj = {
 property1 : 20,
 property2 : this.property1 * -1
}

This doesn't work, but I think it illustrates what I want to accomplish. 这行不通,但我认为它说明了我想要完成的工作。

You can't do that. 你不能那样做。 You can assign it later, though: 您可以稍后分配它:

var myObj = {
    property1: 20
};

myObj.property2 = -myObj.property1;

I could suggest you the following 我可以建议你以下

var myObj = {
    property1 : 20,
    get_property2 : function() {
        return this.property1 * -1;
    },
    set_property2 : function(value) {
        this.property1 = value * -1;
    }
}

Edit 编辑

Seems that this is a dependant property so it is readonly. 似乎这是一个从属属性,因此它是只读的。 But I've edited the code so that it is also writable. 但是我已经编辑了代码,使其也可写。

You can use this: 您可以使用此:

var myObj = {
   property1 : 20,
   get property2() {    return this.property1 * -1;   }
};

But you can only read property2 property. 但是您只能读取property2属性。

Defining setter of property2 will not be a problem. 定义property2 setter不会有问题。 See JavaScript Getters and Setters link. 请参阅JavaScript Getters和Setters链接。

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

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