【问题标题】:Passing prototype's method to a higher order function javascript [duplicate]将原型的方法传递给高阶函数javascript [重复]
【发布时间】:2017-10-14 17:45:37
【问题描述】:

我如何使用原型的方法与this 在更高阶的函数(如reduce)中引用原型?

示例代码:

function A() {

  this.names = ["John", "Jane", "Doe"];

  this.printMergedNamesByIndexes = function() {
    const indicies = [0,1,2]
    console.log(indicies.reduce(this.mergeNames, ""))
  };

  this.mergeNames = function(accumulator, index) {
    return accumulator + this.names[index] + ", "
  };
}

const a = new A()
a.printMergedNamesByIndexes()

我想将原型的mergeNames 方法传递给reduce 函数,但在这种情况下,mergeNames 方法中的 this 值并不引用原型本身。所以我得到了一个错误:

TypeError: undefined is not an object (evaluating 'this.names[index]')

我发现了这个帖子:Using prototype functions in higher order functions in javascript,但 bind 方法给了我一个类似上面的错误,除了它抱怨不存在 bind 方法。

【问题讨论】:

  • mergeNames 不是原型方法(我在您的代码中没有看到任何 prototype)而是一个实例方法,尽管它没有任何区别:您确实应该使用 @987654333 @。请向我们展示您使用它的尝试。

标签: javascript prototype this reduce higher-order-functions


【解决方案1】:

解决方案是使用 lambda/arrow 函数

Arrow functions MDN web docs

箭头函数不会创建自己的 this;使用封闭执行上下文的 this 值。

这意味着将箭头函数传递给更高阶函数将捕获当前作用域的this 值。在这种情况下,这意味着它将原型对象捕获为this,因此我们可以在箭头函数中使用它的方法。

function A() {

  this.names = ["John", "Jane", "Doe"];

  this.printMergedNamesByIndexes = function() {
    const indicies = [0,1,2]
    console.log(indicies.reduce(this.merge, ""))
  };

  // Arrow function
  this.merge = (accumulator, index) => {
    // "this" referencing to the prototype
    return accumulator + this.names[index] + ", "
  };
}

const a = new A()
a.printMergedNamesByIndexes()

【讨论】:

  • 或者你可以做indicies.reduce(this.merge.bind(this), "")
  • ... 或完全停止使用thisprototype
  • @PeterMader 使用原型是一种不好的做法吗?我不经常使用Js,你能解释一下吗?
  • 嗯,我主要使用 JavaScript 进行函数式编程,而不是处理面向对象的编程和继承。但是有一些方法可以绕过原型(例如,免费编程;更多信息herehere)。但这有点古怪,大多数人坚持使用原型继承(或假的基于类的继承,因为他们不了解原型)。
  • @PeterMader 你可能想注意到他根本没有使用prototype
猜你喜欢
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2018-09-01
  • 2012-11-13
  • 2021-02-25
相关资源
最近更新 更多