call 和 apply软吐,調(diào)用一個對象的函數(shù)瘩将,用另一個對象取代當前對象,this 指向轉(zhuǎn)變。兩者區(qū)別:參數(shù)個數(shù)姿现。
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name: ${this.first_name} ${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul Adams
person.displayName.call(person2); // Here we are setting value of this to be person2 object
//Prints Name: Paul Adams
bind:創(chuàng)建一個方法肠仪,并且 this 指針指向當前的指定的對象
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;
this.displayName = function() {
console.log(`Name: ${this.first_name} ${this.last_name}`);
}
}
let person = new Person("John", "Reed");
person.displayName(); // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName(); // Prints Name: Paul Adams
let person2Display = person.displayName.bind(person2); // Creates new function with value of “this” equals to person2 object
person2Display(); // Prints Name: Paul Adams
對學習抱有熱情的開發(fā)小伙伴歡迎加入 qq群685421881,更歡迎熱愛編程的妹子進入备典,讓我們一起學習 并進步吧异旧!