名为method的Javascript函数
我发现了一个使用原型的实现。这是显示结构的简化:名为method的Javascript函数,javascript,oop,methods,Javascript,Oop,Methods,我发现了一个使用原型的实现。这是显示结构的简化: 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
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的函数。你得到的只是函数和方法是如何定义和使用的。当我查看forEach文档时,似乎也没有任何信息
这对任何人都有意义吗
method(t, "push")
将被定义为:
function method(obj, name) {
return obj[name].bind(obj);
}
那辆forEach看起来像
这种方法可能看起来像这样小心:胡乱猜测,为您提供用作迭代器参数的函数
function method(obj, name){
if(typeof(obj[name]) != "function")
throw new Error("Not a function");
return obj[name];
}
这样一个函数,它完全满足您的需求。此外,forEach方法可以是内置的,也可以是内置的
[1,2,3].forEach(_.bindKey(t, 'push'));
然而,这是有效的,因为Thinghiepush只需要一个参数。如果对数组进行相同的调用,结果将与预期不符,因为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]]
在这种情况下,以及在任何情况下,当我们希望方法返回的函数只应用于一个参数时,我猜解决方案是编写
function method(obj, name) {
return function(arg) { return obj[name](arg); }
}
那些forEach和method不是标准函数。您必须查看正在使用的库。打开控制台并键入方法,然后按Enter键。您将看到函数定义。
function method(obj, name) {
return function(arg) { return obj[name](arg); }
}