繁体   English   中英

带有实例方法的Javascript Array.prototype.map函数

[英]Javascript Array.prototype.map function with instance methods

我想知道是否可以将实例方法传递给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的解决方案。

我认为没有创建新函数就不能严格做到这一点,但是可以通过现有函数绑定到某个值来避免函数表达式和声明。

例如,您可以使用Function.prototype.call来使用适当的this值调用Node.prototype.isBig

var result = myArray.map(Function.prototype.call.bind(Node.prototype.isBig));

还有一个绑定运算符的建议,我认为这样可以允许

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中,您可以考虑使用箭头功能

var result = myArray.map(node => node.isBig());

您必须创建一个将node作为其参数的函数(也就是说,它不依赖this

Node.isBig = function(node) {
  return node.isBig();
};

//works because function doesn't depend on this
myArray.map(Node.isBig);
// doesn't work, depends on this
myArray.map(Node.prototype.isBig);

或者,您可以创建一个函数,该函数返回另一个函数,该函数采用其第一个参数并this调用它

 function passFirstArgAsThis (fun) {
     return function() {
         fun.apply(arguments[0], arguments);
     }
 }
 myArray.map( passFirstArgAsThis(Node.prototype.isBig));

更加隐秘的实现是

function passFirstArgAsThis(fn) {
    return function() {
        return fn.call.apply(fn, arguments);  
    };
}

ES6中的等效项更具可读性

function passFirstArgAsThis(fn) {
    return function() {
        // arguments[0] will be the first argument passed to call
        // map will pass it as the node, we will make it become `this`
        // when calling the passed in function
        return fn.call(...arguments); 
    };
}

了解到这一点, Oriol的答案将变得更容易理解

function passFirstArgAsThis(fn) {
    // we return a bound function that will execute the call method, bound
    // to the same passed in function 
    return fn.call.bind(fn);
    // Same as 
    // return function() {
    //    return fn.call(...arguments);
    // }
}

就个人而言,我将使用粗箭头功能以提高可读性,而不需要额外的“静态”功能。

nodes.map(n=>n.isBig())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM