执行对象的功能/方法(Execute function/method of an object)

编程入门 行业动态 更新时间:2024-10-24 13:17:41
执行对象的功能/方法(Execute function/method of an object)

有没有办法在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.

更多推荐

本文发布于:2023-07-05 01:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1031260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   功能   方法   Execute   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!