【发布时间】: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