2012-09-02 77 views
0

你好,我發現計算器如何調用動態功能的物品:調用動態jQuery函數

function mainfunc(func) { 
    this[func].apply(this, Array.prototype.slice.call(arguments, 1)); 
} 

這是非常有用的。但是我怎樣才能在我的對象函數中調用一個函數?

我得到一個錯誤:

"TypeError: this[func] is undefined this[func].apply(this, Array.prototype.slice.call(arguments, 1));"

它看起來像:

var myScript = { 
... 
add : function() { 
... 
myScript.ajax('url.php', params, 'myScript.add2List'); 
}, 

add2List : function(data) { 
console.log(data); 
}, 

ajax : function(url, params, func) { 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: params, 
     success: function(data) { 
     console.log(func); 
     mainfunc(func, data); 
     } 
    }); 
} 
} 

回答

0

你不需要使用該功能,你可以做以下代替。

var myScript = { 
... 
add : function() { 
    ... 
    myScript.ajax('url.php', params, this.add2List); 
}, 

add2List : function(data) { 
    console.log(data); 
}, 

ajax : function(url, params, func) { 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: params, 
     success: func 
    }); 
} 
} 
+0

嗨xdazz。非常感謝你這樣做。但它不適用於「這個」,我不得不寫「myScript」。它找不到 - 不知道;) – user1509034