【发布时间】:2020-05-16 15:53:00
【问题描述】:
我遇到了一个我无法理解的问题。所以我创建了一个包含几个函数的新函数。这是我的代码:
(() => {
function BetterArray(array) {
this.array = array;
}
BetterArray.prototype.map = function (fn) {
return Array.prototype.map.call(this.array, fn);
};
BetterArray.prototype.collect = function (fn) {
return Array.prototype.map.call(this.array, fn);
};
const a = new BetterArray([1])
.map((item) => item * 2)
.collect((item) => item * 2);
console.log(a);
})();
在“收集”行中我收到错误未捕获的类型错误:(中间值).map(...).collect 不是函数。我只是好奇为什么会出现这个错误,以及如何正确编写这段代码来避免这种情况。另外一点是,当我用 collect 更改 map - 我没有收到此错误。
我知道这两个函数是相同的,但我想确定它不是基于函数体的。
感谢您的宝贵时间!
【问题讨论】:
-
BetterArray.prototype.map是否返回BetterArray或Array的实例? -
我不确定,我尝试查看
Object.getPrototypeOf(a)并且似乎这是 Array.prototype ... 那么当我使用“调用”fn 时,我如何才能“保留”旧原型?
标签: javascript function prototypejs