新创建的原型中的中间值
Intermediate value in new created prototype
我遇到了一个我无法理解的问题。所以我创建了一个包含几个函数的新函数。这是我的代码:
(() => {
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);
})();
在行 "collect" 中,我收到一个错误 Uncaught TypeError: (intermediate value).map(...).collect is not a function。我只是好奇为什么会出现此错误,以及如何正确编写此代码以避免这种情况。另外一点是,当我将 map 更改为 collect - 我没有收到此错误。
我知道这两个函数是一样的,但我想确定它不是基于函数体的。
感谢您的宝贵时间!
现在,.map
和 .collect
方法 returning 普通数组 ,普通数组没有 .collect
方法。
当您在 BetterArray
上调用 .map
时,如果您希望能够调用 BetterArray
之后像 .collect
这样的方法:
(() => {
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
方法应用相同的逻辑)
我遇到了一个我无法理解的问题。所以我创建了一个包含几个函数的新函数。这是我的代码:
(() => {
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);
})();
在行 "collect" 中,我收到一个错误 Uncaught TypeError: (intermediate value).map(...).collect is not a function。我只是好奇为什么会出现此错误,以及如何正确编写此代码以避免这种情况。另外一点是,当我将 map 更改为 collect - 我没有收到此错误。
我知道这两个函数是一样的,但我想确定它不是基于函数体的。
感谢您的宝贵时间!
现在,.map
和 .collect
方法 returning 普通数组 ,普通数组没有 .collect
方法。
当您在 BetterArray
上调用 .map
时,如果您希望能够调用 BetterArray
之后像 .collect
这样的方法:
(() => {
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
方法应用相同的逻辑)