<分区>
我正在尝试创建一个 JSON 对象来存储程序的一些参数。一些参数需要在定义时根据其他参数计算得出。我想在对象定义中这样做,但也许这是不可能的
var params = {
a: 50,
b: 70,
c: this.a+this.b
}
结果
发生了什么
>params.c
NaN
我希望发生的事
>params.c
120
编辑
进一步阅读后,我想我正在使用对象文字表示法而不是 JSON。
<分区>
我正在尝试创建一个 JSON 对象来存储程序的一些参数。一些参数需要在定义时根据其他参数计算得出。我想在对象定义中这样做,但也许这是不可能的
var params = {
a: 50,
b: 70,
c: this.a+this.b
}
结果
发生了什么
>params.c
NaN
我希望发生的事
>params.c
120
编辑
进一步阅读后,我想我正在使用对象文字表示法而不是 JSON。
最佳答案
您可以使用这种方法:
为避免重新计算,请使用函数 Object.assign
。
The
get
syntax binds an object property to a function that will be called when that property is looked up.
var params = {
a: 50,
b: 70,
get c() {
console.log('Called!');
return this.a + this.b;
}
};
console.log(params.c); // Prints 120 then Called!
console.log(params.c); // Prints 120 then Called!
var params = Object.assign({}, {
a: 50,
b: 70,
get c() {
console.log('Called from function Object.assign!');
return this.a + this.b;
}
});
params.a = 1000; // To illustrate.
console.log(params.c); // Prints 120
console.log(params.c); // Prints 120
.as-console-wrapper {
max-height: 100% !important
}
关于javascript - 使用内部定义变量的 JSON 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48757599/
相关文章:
javascript - 更改 Google Maps JavaScript API v3 圈外的 map 不透明度
JavaScript:剥离元数据中的 URL,而不剥离所有字符串中的空格
javascript - JSON+Node.js - 意外的 token o
javascript - 使用对象属性在 for 循环中声明变量
javascript - 将javascript对象转换为 Backbone 模型
c++ - 警告 : non-static data member initializers only available with -std=c++11 or -std=gnu++11?