2017-08-01 88 views
3

的函数/方法有没有办法让这样的事情在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(),则不存在任何问题。不是非常重要,但我只是想知道并找不到答案。

+0

嗯,是的,你应该使用'x.a()'。你真正的问题是什么? – Bergi

+1

在回调 – Bergi

+2

中尝试使用'f(obj [prop])'和'val => val()'作为回调,或者使用'x [prop]()'将属性名称的字符串传递给'f '所以发生的事情真的是''a'.a();'not'x ['a']();' –

回答

3

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

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

+0

谢谢是答案,我不知道道具只是关键。 – meow

1

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(); 
 
});