我希望当我在 Js 中创建一个对象时能够定义一个属性,包括同一对象的前一个属性的值(因此,如果我想用其他属性的一部分定义一个属性,则不要重复元素),但我不知道这是否可能。我给你看我的代码:var Sel = { timSand: document.getElementById('tim-sand'), timSandHei: getComputedStyle(timSand).height, // not Working}var Sel = { timSand: document.getElementById('tim-sand'), timSandHei: getComputedStyle(document.getElementById('tim-sand')).height, // Working but a bit dirty}所以当我做第一个例子时,我有一个错误,我必须timSand在第二行中替换为document.getElementById('tim-sand'),就像在第二个例子中一样。你知道避免这种情况的方法吗?
1 回答

Smart猫小萌
TA贡献1911条经验 获得超7个赞
你不能,因为对象还不存在,所以你不能引用它。
但是您可以使用变量来避免繁重的 DOM 访问。
var sand = document.getElementById('tim-sand')
var Sel = {
timSand: sand,
timSandHei: getComputedStyle(sand).height, //Working
}
添加回答
举报
0/150
提交
取消