差異
bind 和 call 傳參方式一樣,但是bind返回的是一個函數(shù),綁定this,且可傳遞預(yù)置參數(shù)
call 和 apply 傳參方式不一樣,apply接收兩個參數(shù),第二個參數(shù)是一個參數(shù)數(shù)組
這三個都是用來重定義 this 這個對象的,下面的例子可以簡單看出幾個方法的不同
var student = {
name: "高三學(xué)生",
age:18,
sayHi: function (province,city) {
console.log("HI~我是" + this.name +",今年"+this.age+ ",來自" + province+city);
},
};
var san = {
name: "張三",
age :20
};
student.sayHi.call(san,'湖南','長沙')
student.sayHi.apply(san,['湖南','長沙'])
student.sayHi.bind(san,'湖南','長沙')()
// 三個打印出來
// HI~我是張三,今年20,來自湖南長沙
實現(xiàn)這三個方法
Function.prototype.apply = function(context = window, args) {
if (typeof this !== 'function') {
throw new TypeError('Type Error');
}
const fn = Symbol('fn');
context[fn] = this;
const res = context[fn](...args);
delete context[fn];
return res;
}
Function.prototype.call = function(context = window, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Type Error');
}
const fn = Symbol('fn');
context[fn] = this;
const res = context[fn](...args);
delete context[fn];
return res;
}
Function.prototype.bind = function(context, ...args) {
if (typeof this !== 'function') {
throw new Error("Type Error");
}
// 保存this的值
var self = this;
return function F() {
// 考慮new的情況
if(this instanceof F) {
return new self(...args, ...arguments)
}
return self.apply(context, [...args, ...arguments])
}
}