call、apply、bind
阿新 • • 發佈:2020-09-19
call
定義:呼叫一個物件的一個方法,以另一個物件替換當前物件,傳遞多個引數
Person.prototype.sayHi=function (x,y) {
console.log("您好啊:"+this.sex);
return 1000;
};
var per=new Person(10,"男");
function Student(name,sex) {
this.name=name;
this.sex=sex;
}
var stu=new Student("小明","人妖");
var r2=per.sayHi.call(stu,10,20);
apply
定義:應用某一物件的一個方法,用另一個物件替換當前物件,apply傳遞多個引數的時候第二個引數需要傳遞一個數組
Person.prototype.sayHi=function (x,y) {
console.log("您好啊:"+this.sex);
return 1000;
};
var per=new Person(10,"男");
function Student(name,sex) {
this.name=name;
this.sex=sex;
}
var stu=new Student("小明","人妖");
var r1=per.sayHi.apply(stu,[10,20]);
call/bind區別
call 和 apply 都是為了解決改變 this 的指向。作用都是相同的,只是傳參的方式不同
bind
bind也能改變this的指向,返回一個修改過的函式,但該函式不會被執行
function f1(x, y) {
console.log((x + y) + ":=====>" + this.age);
}
function Person() {
this.age = 1000;
}
Person.prototype.eat = function () {
console.log("這個是吃");
};
var per = new Person();
var ff = f1.bind(per, 10, 20);
- applay、call和bind的卻別在於前者立即執行,後者在需要的時候執行
實現一個call函式
Function.prototype.myCall = function (context) {
var context = context || window
// 給 context 新增一個屬性,這裡的this就是new出來的例項化物件
context.fn = this
// 將 context 後面的引數取出來
var args = [...arguments].slice(1)
var result = context.fn(...args)
// 刪除 fn
delete context.fn
return result
}
實現一個apply函式
Function.prototype.myApply = function (context) {
var context = context || window
context.fn = this
var result
// 需要判斷是否儲存第二個引數
// 如果存在,就將第二個引數展開
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
豌豆資源搜尋網站https://55wd.com 廣州vi設計公司http://www.maiqicn.com
實現一個bind函式
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
var _this = this
var args = [...arguments].slice(1)
// 返回一個函式
return function F() {
// 因為返回了一個函式,我們可以 new F(),所以需要判斷
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}