【发布时间】:2019-09-13 20:59:18
【问题描述】:
有人可以向我解释一下数组方法是如何知道我们调用它们的值的吗? 作为原型继承的一部分,它不应该存在于 Array.prototype 如果我们说
let animals = ['dog','cat']
animals.map( x => console.log(x))
//dog
//cat
我只是不明白 map 是如何知道我们通过了 ['dog','cat'] 的。 我通常看到,如果你调用一个函数,那么你需要像 map(animals) 一样调用它。
提前谢谢你
或查看地图 polyfill,我们将其分配给数组参数的行在哪里。
if (!Array.prototype.map) {
Array.prototype.map = function(callback/*, thisArg*/) {
var T, A, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = arguments[1];
}
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
【问题讨论】:
-
这是 JavaScript 原型继承的魔力,再加上在函数调用中如何设置
this的规则。 -
为什么要否决这个问题?
-
Array.prototype.map()与分配给对象的任何其他方法没有什么不同。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…arr.map(function callback(currentValue[, index[, array]]) { -
你知道普通方法如何知道它们被调用的对象吗?喜欢
obj.f()上的const obj = { x: 1, f() { console.log(this); }};? -
@JSLover 为什么参数会改变
this在方法中指向的内容?
标签: javascript