2017-08-01 59 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(); 
 
});