JavaScript中 call 、apply 和 bind

call 和 apply,调用一个对象的函数,用另一个对象取代当前对象,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

person.displayName.call(person2); // Here we are setting value of this to be person2 object
//Prints Name: Paul Adams

bind:创建一个方法,并且 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

对学习抱有热情的开发小伙伴欢迎加入 qq群685421881,更欢迎热爱编程的妹子进入,让我们一起学习 并进步吧!

推荐阅读更多精彩内容