2016-11-24 52 views
0

我有一個函數,它接受一個字符串。該函數檢查列表中的對象是否具有此函數(functionName)。如果它包含該功能,我該如何返回它?很明顯,return list[i].message would work,但那不是什麼即時通訊之後。我想在這種情況下使用參數functionName。Javascript - 查看對象是否包含函數,如果有,返回它

function message(){ 
    return "hello"; 
} 

function test(functionName); 
    listLength = list.length; 
    for(i = 0; i < listLength; i++){ 
     if(list[i].hasOwnProperty(functionName}{ 

      return (?) 
    } 
} 
var x = test("message"); 
alert(x); 

感激響應

+7

'return list [i] [functionName]' – Pointy

+2

你也想添加到'if'條件'&& typeof list [i] [functionName] ==「function」 –

回答

0

Pointy的評論是正確的,但你必須考慮到,具有它的主人分離的功能會搞砸的範圍,所以你將不再有機會獲得this對象

var test = { 
    number: 0, 
    testFunction: function() { 
     return this.number; 
    } 
} 

console.log(test.testFunction()); // output: 0 

var x = test.testFunction; 
console.log(x());     // output: undefined 

也許你應該使用

var y = test.testFunction.bind(test); 
console.log(y());     // output: 0 
相關問題