https://blog.csdn.net/qq_40479190/article/details/78324270
call
一句話介紹 call:
call() 方法在使用一個指定的 this 值和若干個指定的參數值的前提下調用某個函數或方法。
舉個例子:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call(foo); // 1
注意兩點:
call 改變了 this 的指向,指向到 foo
bar 函數執行了
模擬實現第一步
那麼我們該怎麼模擬實現這兩個效果呢?
試想當調用 call 的時候,把 foo 對象改造成如下:
var foo = {
value: 1,
bar: function() {
console.log(this.value)
}
};
foo.bar(); // 1
這個時候 this 就指向了 foo,是不是很簡單呢?
但是這樣卻給 foo 對象本身添加了一個屬性,這可不行吶!
不過也不用擔心,我們用 delete 再刪除它不就好了~
所以我們模擬的步驟可以分爲:
將函數設爲對象的屬性
執行該函數
刪除該函數
以上個例子爲例,就是:
// 第一步
foo.fn = bar
// 第二步
foo.fn()
// 第三步
delete foo.fn
fn 是對象的屬性名,反正最後也要刪除它,所以起成什麼都無所謂。
根據這個思路,我們可以嘗試着去寫第一版的 call2 函數:
// 第一版
Function.prototype.call2 = function(context) {
// 首先要獲取調用call的函數,用this可以獲取
context.fn = this;
context.fn();
delete context.fn;
}
// 測試一下
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call2(foo); // 1
正好可以打印 1 哎!是不是很開心!(~ ̄▽ ̄)~
模擬實現第二步
最一開始也講了,call 函數還能給定參數執行函數。舉個例子:
var foo = {
value: 1
};
function bar(name, age) {
console.log(name)
console.log(age)
console.log(this.value);
}
bar.call(foo, 'kevin', 18);
// kevin
// 18
// 1
注意:傳入的參數並不確定,這可咋辦?
不急,我們可以從 Arguments 對象中取值,取出第二個到最後一個參數,然後放到一個數組裏。
比如這樣:
// 以上個例子爲例,此時的arguments爲:
// arguments = {
// 0: foo,
// 1: 'kevin',
// 2: 18,
// length: 3
// }
// 因爲arguments是類數組對象,所以可以用for循環
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
// 執行後 args爲 [foo, 'kevin', 18]
不定長的參數問題解決了,我們接着要把這個參數數組放到要執行的函數的參數裏面去。
// 將數組裏的元素作爲多個參數放進函數的形參裏
context.fn(args.join(','))
// (O_o)??
// 這個方法肯定是不行的啦!!!
也許有人想到用 ES6 的方法,不過 call 是 ES3 的方法,我們爲了模擬實現一個 ES3 的方法,要用到ES6的方法,好像……,嗯,也可以啦。但是我們這次用 eval 方法拼成一個函數,類似於這樣:
eval('context.fn(' + args +')')
這裏 args 會自動調用 Array.toString() 這個方法。
所以我們的第二版克服了兩個大問題,代碼如下:
// 第二版
Function.prototype.call2 = function(context) {
context.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
eval('context.fn(' + args +')');
delete context.fn;
}
// 測試一下
var foo = {
value: 1
};
function bar(name, age) {
console.log(name)
console.log(age)
console.log(this.value);
}
bar.call2(foo, 'kevin', 18);
// kevin
// 18
// 1
(๑•̀ㅂ•́)و✧
模擬實現第三步
模擬代碼已經完成 80%,還有兩個小點要注意:
1.this 參數可以傳 null,當爲 null 的時候,視爲指向 window
舉個例子:
var value = 1;
function bar() {
console.log(this.value);
}
bar.call(null); // 1
雖然這個例子本身不使用 call,結果依然一樣。
2.函數是可以有返回值的!
舉個例子:
var obj = {
value: 1
}
function bar(name, age) {
return {
value: this.value,
name: name,
age: age
}
}
console.log(bar.call(obj, 'kevin', 18));
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }
不過都很好解決,讓我們直接看第三版也就是最後一版的代碼:
// 第三版
Function.prototype.call2 = function (context) {
var context = context || window;
context.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
var result = eval('context.fn(' + args +')');
delete context.fn
return result;
}
// 測試一下
var value = 2;
var obj = {
value: 1
}
function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}
bar.call(null); // 2
console.log(bar.call2(obj, 'kevin', 18));
// 1
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }
到此,我們完成了 call 的模擬實現,給自己一個贊 b( ̄▽ ̄)d
apply的模擬實現
apply 的實現跟 call 類似,在這裏直接給代碼,代碼來自於知乎 @鄭航的實現:
Function.prototype.apply = function (context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
}
delete context.fn
return result;
}
類數組轉對象
在上面的例子中已經提到了一種類數組轉數組的方法,再補充三個:
var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 1. slice
Array.prototype.slice.call(arrayLike); // ["name", "age", "sex"]
// 2. splice
Array.prototype.splice.call(arrayLike, 0); // ["name", "age", "sex"]
// 3. ES6 Array.from
Array.from(arrayLike); // ["name", "age", "sex"]
// 4. apply
Array.prototype.concat.apply([], arrayLike)
要說到類數組對象,Arguments 對象就是一個類數組對象。
在客戶端 JavaScript 中,一些 DOM 方法(document.getElementsByTagName()等)也返回類數組對象。
傳遞參數
將參數從一個函數傳遞到另一個函數
// 使用 apply 將 foo 的參數傳遞給 bar
function foo() {
bar.apply(this, arguments);
}
function bar(a, b, c) {
console.log(a, b, c);
}
foo(1, 2, 3)
強大的ES6
使用ES6的 … 運算符,我們可以輕鬆轉成數組。
function func(...arguments) {
console.log(arguments); // [1, 2, 3]
}
func(1, 2, 3);
bind
一句話介紹 bind:
bind() 方法會創建一個新函數。當這個新函數被調用時,bind() 的第一個參數將作爲它運行時的 this,之後的一序列參數將會在傳遞的實參前傳入作爲它的參數。(來自於 MDN )
由此我們可以首先得出 bind 函數的兩個特點:
返回一個函數
可以傳入參數
返回函數的模擬實現
從第一個特點開始,我們舉個例子:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
// 返回了一個函數
var bindFoo = bar.bind(foo);
bindFoo(); // 1
關於指定 this 的指向,我們可以使用 call 或者 apply 實現,關於 call 和 apply 的模擬實現,可以查看《JavaScript深入之call和apply的模擬實現》。我們來寫第一版的代碼:
// 第一版
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
self.apply(context);
}
}
傳參的模擬實現
接下來看第二點,可以傳入參數。這個就有點讓人費解了,我在 bind 的時候,是否可以傳參呢?我在執行 bind 返回的函數的時候,可不可以傳參呢?讓我們看個例子:
var foo = {
value: 1
};
function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18
函數需要傳 name 和 age 兩個參數,竟然還可以在 bind 的時候,只傳一個 name,在執行返回的函數的時候,再傳另一個參數 age!
這可咋辦?不急,我們用 arguments 進行處理:
// 第二版
Function.prototype.bind2 = function (context) {
var self = this;
// 獲取bind2函數從第二個參數到最後一個參數
var args = Array.prototype.slice.call(arguments, 1);
return function () {
// 這個時候的arguments是指bind返回的函數傳入的參數
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(context, args.concat(bindArgs));
}
}
構造函數效果的模擬實現
完成了這兩點,最難的部分到啦!因爲 bind 還有一個特點,就是
一個綁定函數也能使用new操作符創建對象:這種行爲就像把原函數當成構造器。提供的 this 值被忽略,同時調用時的參數被提供給模擬函數。
也就是說當 bind 返回的函數作爲構造函數的時候,bind 時指定的 this 值會失效,但傳入的參數依然生效。舉個例子:
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin
注意:儘管在全局和 foo 中都聲明瞭 value 值,最後依然返回了 undefind,說明綁定的 this 失效了,如果大家瞭解 new 的模擬實現,就會知道這個時候的 this 已經指向了 obj。
(哈哈,我這是爲我的下一篇文章《JavaScript深入系列之new的模擬實現》打廣告)。
所以我們可以通過修改返回的函數的原型來實現,讓我們寫一下:
// 第三版
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
// 當作爲構造函數時,this 指向實例,此時結果爲 true,將綁定函數的 this 指向該實例,可以讓實例獲得來自綁定函數的值
// 以上面的是 demo 爲例,如果改成 `this instanceof fBound ? null : context`,實例只是一個空對象,將 null 改成 this ,實例會具有 habit 屬性
// 當作爲普通函數時,this 指向 window,此時結果爲 false,將綁定函數的 this 指向 context
self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
}
// 修改返回函數的 prototype 爲綁定函數的 prototype,實例就可以繼承綁定函數的原型中的值
fBound.prototype = this.prototype;
return fBound;
}
如果對原型鏈稍有困惑,可以查看《JavaScript深入之從原型到原型鏈》。
構造函數效果的優化實現
但是在這個寫法中,我們直接將 fBound.prototype = this.prototype,我們直接修改 fBound.prototype 的時候,也會直接修改綁定函數的 prototype。這個時候,我們可以通過一個空函數來進行中轉:
// 第四版
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
到此爲止,大的問題都已經解決,給自己一個贊!o( ̄▽ ̄)d
三個小問題
接下來處理些小問題:
1.apply 這段代碼跟 MDN 上的稍有不同
在 MDN 中文版講 bind 的模擬實現時,apply 這裏的代碼是:
self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))
多了一個關於 context 是否存在的判斷,然而這個是錯誤的!
舉個例子:
var value = 2;
var foo = {
value: 1,
bar: bar.bind(null)
};
function bar() {
console.log(this.value);
}
foo.bar() // 2
以上代碼正常情況下會打印 2,如果換成了 context || this,這段代碼就會打印 1!
所以這裏不應該進行 context 的判斷,大家查看 MDN 同樣內容的英文版,就不存在這個判斷!
2.調用 bind 的不是函數咋辦?
不行,我們要報錯!
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
3.我要在線上用
那別忘了做個兼容:
Function.prototype.bind = Function.prototype.bind || function () {
……
};
當然最好是用 es5-shim 啦。
最終代碼
所以最最後的代碼就是:
Function.prototype.bind2 = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}