gpt4 book ai didi

javascript - 如何将公共(public)属性添加到所有对象的属性(速记)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:17 25 4
gpt4 key购买 nike

我的 Object 的每个属性都有公共(public)属性(称为:selected),是否有一种简短的方法可以将此属性注入(inject)每个属性没有明确地写出每一个?

请注意,我已经查看了这个 answer但它只谈论数组

var myObject = {
propery1: {
selected: function () {
return this.value === someVariable;
},
value: 1,
},
propery2: {
selected: function () {
return this.value === someVariable;
},
value: 2,
},
propery3: {
selected: function () {
return this.value === someVariable;
},
value: 3,
},

//...

propery10: {
selected: function () {
return this.value === someVariable;
},
value: 10,
},
};

例如:

var someVariable = 1;

输出:

myObject = {
propery1: {
selected: true,
value: 1,
},
propery2: {
selected: false,
value: 2,
},
propery3: {
selected: false,
value: 3,
},

//...

propery10: {
selected: false,
value: 10,
},
};

最佳答案

您可以绑定(bind)内部对象,调用函数并分配值。

var object = { propery1: { selected: function () { return this.value === someVariable; }, value: 1 }, propery2: { selected: function () { return this.value === someVariable; }, value: 2 }, propery3: { selected: function () { return this.value === someVariable; }, value: 3 }, propery10: { selected: function () { return this.value === someVariable; }, value: 10 } },
someVariable = 1;

Object.keys(object).forEach(k => object[k].selected = object[k].selected.call(object[k]));

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何将公共(public)属性添加到所有对象的属性(速记),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48666017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com