【问题标题】:Intermediate value in new created prototype新创建原型的中间值
【发布时间】: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 是否返回 BetterArrayArray 的实例?
  • 我不确定,我尝试查看Object.getPrototypeOf(a) 并且似乎这是 Array.prototype ... 那么当我使用“调用”fn 时,我如何才能“保留”旧原型?

标签: javascript function prototypejs


【解决方案1】:

现在,.map.collect 方法正在返回普通数组,而普通数组上没有 .collect 方法。

当您在 BetterArray 上调用 .map 时,如果您希望之后能够在其上调用 BetterArray 之类的 .collect 方法,则应该创建并返回 BetterArray 的新实例:

(() => {
    function BetterArray(array) {
        this.array = array;
    }

    BetterArray.prototype.map = function (fn) {
        const arr = Array.prototype.map.call(this.array, fn);
        const newBetterArr = new BetterArray(arr);
        return newBetterArr;
    };

    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);
})();

(如果您希望 .collect 也产生 BetterArray 实例,请对 .collect 方法应用相同的逻辑)

【讨论】:

  • 好的,现在知道了.. 所以现在如果我想从其他原型调用其他方法,并且如果这些方法返回像字符串这样的普通对象 - 那么我应该返回我的原型的新实例吗?
  • 对,如果您希望链式调用产生相同类型的对象,请在方法末尾返回一个新实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2021-11-27
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多