我想知道是否可以将实例方法传递到 Array.prototype.map 函数中。
例如,我基本上想要这个功能,而不必制作单独的函数
function Node(n) {
this.val = n;
}
Node.prototype.isBig = function() {
return this.val > 5;
}
var myArray = [
new Node(1), new Node(2), new Node(3),
new Node(7), new Node(8), new Node(9)
];
console.log(myArray);
var result = myArray.map(function(node) {
return node.isBig();
});
console.log(result);
在java中我可以做.map(Node::isBig)
。我可以做一些事情来更改 map 参数,这样我就不必创建函数了吗?
如果你无法使用 vanilla js 实现,我也愿意接受 lodash 的解决方案。
最佳答案
我认为你不能在不创建新函数的情况下严格做到这一点,但你可以通过 binding 避免函数表达式和声明现有功能具有一定的值(value)。
例如,您可以使用 Function.prototype.call
使用适当的 this
值调用 Node.prototype.isBig
。
var result = myArray.map(Function.prototype.call.bind(Node.prototype.isBig));
还有一个bind operator的提案,我认为它会允许
var result = myArray.map(::Node.prototype.isBig.call);
请注意,其他参数(索引和数组)将传递给 isBig
方法。
function Node(n) {
this.val = n;
}
Node.prototype.isBig = function() {
return this.val > 5;
};
var myArray = [
new Node(1), new Node(2), new Node(3),
new Node(7), new Node(8), new Node(9)
];
var result = myArray.map(Function.prototype.call.bind(Node.prototype.isBig));
document.write(JSON.stringify(result));
而在 ES6 中,可以考虑使用 arrow functions :
var result = myArray.map(node => node.isBig());
关于带有实例方法的 Javascript Array.prototype.map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228710/