1.首先,了解call方法的要点
- 语法:
function.call(thisArg, arg1, arg2, ...)
参数:
1.thisArg
在 function 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
this指向:非严格模式下,指向window。严格模式下,为undefined。
示例:
var a = 2;
var obj = {
name: 'ha',
age: 12,
getSome : function () {
// 'use strict'; 非严格模式下
console.log(this); // window
console.log(a); // 2
}
}
obj.getSome.call(undefined);
---------------------------------------------------------
var a = 2;
var obj = {
name: 'ha',
age: 12,
getSome : function () {
'use strict'; // 严格模式下
console.log(this); // undefined
console.log(a); // 2
}
}
obj.getSome.call(undefined);
- 返回值
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
手动实现时,还必须将值return出来。
2.手动实现call方法
要点:
- 返回值
- 将调用者,转变为this下的一个方法,执行完后,记得删除。
示例:
const obj = {
name: 'ha',
age: 12,
getSome : function (a, b) {
console.log(this);
return a + b;
}
}
Function.prototype.myCall = function (context = window,...args) {
var func = this,
fn = Symbol('fn'); // 确保属性名独一无二
context[fn] = func; // 这里的转变:调用者(函数)作为context对象的方法
var res = context[fn](...args);
delete context[fn]; // 记得将context对象上刚刚新增的func方法删除
return res;
}
const res = obj.getSome.myCall(obj, 1, 2, 3);
console.log(res);
结果如下: