有没有一种方法可以像Lua中的JavaScript中的元可那样索引对象?
例如:
var obj = {a:"a",b:"b",properties:{c:"c",d:"d"}}
metatable(obj,obj.properties) // Make it so that if you try to index something that's not inside the object it will go to the parameter one
console.log(obj.a) // "a"
console.log(obj.c) // "c"对于LMD:如何对多个对象执行此操作?例如:
var objs = [
obj1 = {name:"Button";class:"button";properties:{text:"Press this"}]
]
for (i in objs){
metatable(objs[i],objs[i].properties)
}
console.log(objs.obj1.text) // "Press this"发布于 2022-07-12 15:52:51
是的: JavaScript有原型。它们与Lua不完全相同,但可以用于简单的元索引目的。实现您的示例的一个方法如下:
const properties = {c: "c", d: "d"} // prototype
const obj = Object.create(properties) // create object with prototype
obj.a = "a"; obj.b = "b";
console.log(obj.a) // "a"
console.log(obj.c) // "c"或者,如果您已经给出了对象,如第二个示例所示,您可能希望使用Object.setPrototypeOf(object, prototype),这与Lua中的setmetatable(object, {__index = prototype})类似:
const objs = [{name:"Button", class:"button", properties: {text:"Press this"}}]
for (const obj of objs) Object.setPrototypeOf(obj, obj.properties)
console.log(objs[0].text) // "Press this"也就是说,您一直在搜索的metatable函数实际上是Object.setPrototypeOf!
https://stackoverflow.com/questions/72955059
复制相似问题