Function.prototype.call 是 JavaScript 函数原型中的一个函数,它调用函数,使用第一个参数作为 this 参数,并传递剩余参数作为被调用函数的参数。举个例子:
// this function has `Function` in prototype chain// so `call` is availablefunctionmultiply(x,y){returnx*y;}multiply.call(null,3,5);// 15multiply(3,5);// same, 15
Math.max(1, 2, 3); // if we know all numbers upfront
// we can call it like that
Math.max([1, 2, 3]); // won't work!
Math.max.apply(null, [1, 2, 3]); // will work!
// however, ES2015 array destructuring works as well:
Math.max(...[1, 2, 3]);
// let's try to imagine how trim method is implemented
// on String.prototype
String.prototype.trim = function() {
// string itself is contained inside `this`!
const str = this;
// this is a very naive implementation
return str.replace(/(^\s+)|(\s+$)/g, '');
};
// let's try to use `.call` method to invoke `trim`
" aa ".trim.call(thisArg);
// but `this` is our string itself!
// so, next two calls are equivalent:
" aa ".trim.call(" aa ");
String.prototype.trim.call(" aa ");