[英]A Javascript function named method
我找到了使用原型的實現。 這是顯示結構的簡化:
function Thingie(){
this.content = [];
}
Thingie.prototype = {
push: function(arg) {
this.content.push(arg);
},
pop: function() {
return this.content.pop();
}
};
var t = new Thingie();
forEach([10, 3, 4, 8, 2, 9, 7, 1, 2, 6, 5],
method(t, "push"));
最后一行示例中的“方法”是什么? 我從未見過這種構造。 我像其他人一樣使用t.push。
我嘗試查找如何在線定義“ method()”,但是不可能使用任何可能的搜索詞組來搜索名為“ method”的函數。 您所獲得的只是函數和方法的定義和使用方式。 當我查看forEach文檔時,似乎也沒有任何信息。
這對任何人有意義嗎?
method(t, "push")
將被定義為:
function method(obj, name) {
return obj[name].bind(obj);
}
forEach
看起來像UnderscoreJS的函數_.each
_.each(list, iteratee, [context]) Alias: forEach
example:
_.each([1,2,3], function(item) { console.log(item); });
// console output:
// 1
// 2
// 3
該method
可能看起來像這樣(當心:瘋狂的猜測!),為您提供了用作iteratee
參數的函數
function method(obj, name){
if(typeof(obj[name]) != "function")
throw new Error("Not a function");
return obj[name];
}
像lodash.bindKey這樣的函數正是您想要的。 另外, forEach
方法可以是lodash.forEach ,也可以是內置的Array.prototype.forEach 。
[1,2,3].forEach(_.bindKey(t, 'push'));
但是,這是Thinghie#push
,因為Thinghie#push
只需要一個參數。 如果對數組進行相同的調用,則結果將不會達到預期的效果,因為forEach
方法帶有3個參數: value, index, array
和[].push
可以處理多個參數。 所以,代碼
var array = [];
[1,2].forEach(_.bindKey(array, 'push'));
console.log(array); // outputs [1, 0, [1, 2], 2, 1, [1, 2]]
在這種情況下(無論如何,只要我們希望僅將method
返回的函數應用於一個參數),我想解決方案就是編寫
function method(obj, name) {
return function(arg) { return obj[name](arg); }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.