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);
結果如下: