有没有办法在JS中使用这样的东西:
function iterateObject(obj, f) { for (let prop in obj) { if (obj.hasOwnProperty(prop)) f(prop); } }然后将其应用于对象:
let x = {a : function() { // do smth }}; iterateObject(x, (prop) => { prop.a(); }我得到一个错误,prop.a()不是一个函数,但如果我调用xa()没有问题。 不是非常重要,但我只是想知道,找不到答案。
Is there a way to get something like this to work in JS:
function iterateObject(obj, f) { for (let prop in obj) { if (obj.hasOwnProperty(prop)) f(prop); } }And then apply it on an object:
let x = {a : function() { // do smth }}; iterateObject(x, (prop) => { prop.a(); }I'm getting an error that prop.a() is not a function but if I call x.a() there is no problem. Not super important but I'm just wondering and couldn't find an answer.
最满意答案
在调用iterateObject ,在匿名函数内, prop是字符串"a" 。 此外, x是您的原始对象。
要通过对象( x )上的名称( prop )访问属性,您必须执行x[prop] 。 要调用该函数,您应该在匿名函数中编写x[prop]() 。
In your invocation of iterateObject, inside the anonymous function, prop is the string "a". Also, x is your original object.
To access a property by name (prop) on an object (x), you would have to do x[prop]. To invoke that function, you should write x[prop]() inside your anonymous function.
更多推荐
发布评论