【问题标题】:Execute function/method of an object执行对象的功能/方法
【发布时间】:2017-08-01 20:49:16
【问题描述】:

有没有办法让这样的东西在 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() 不是函数,但如果我调用 x.a() 就没有问题。不是很重要,但我只是想知道并且找不到答案。

【问题讨论】:

  • 嗯,是的,你应该使用x.a()。你的实际问题是什么?
  • 尝试使用f(obj[prop])val => val() 作为回调,或者在回调中使用x[prop]()
  • 属性名称的字符串正在传递给您的f,所以实际上发生的事情是'a'.a(); 而不是x['a']();
  • 当您可以简单地使用 for (let prop in x) 循环时,为什么还要使用带有回调的 iterateObject(x, (prop) => 函数?
  • 迭代多个嵌套对象并为每个对象调用相同的方法,但有许多这样的嵌套对象具有不同的调用方法,这样可以减少代码。

标签: javascript function object


【解决方案1】:

在您调用iterateObject 时,在匿名函数内部,prop 是字符串"a"。另外,x 是您的原始对象。

要在对象 (x) 上按名称 (prop) 访问属性,您必须执行 x[prop]。要调用该函数,您应该在匿名函数中写入 x[prop]()

【讨论】:

  • 谢谢这是答案,我有点不知道道具只是关键。
【解决方案2】:

function iterateObject(obj, f) {
  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      f(obj[prop]); 
      // You were earlier just passing the key 'a' as a string to the function.
      // Hence it was giving you an error
      // You need to pass the function i.e obj[prop]
    }
  }
}

let x = {
  a: function() {
    console.log('hello');
  }
};

iterateObject(x, (prop) => {
  // You will get the function as prop
  // To execute it you need to directly call it using prop()
  prop();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多