编程语言
首页 > 编程语言> > 【JavaScript】call()、apply()、bind()的用法和区别

【JavaScript】call()、apply()、bind()的用法和区别

作者:互联网

这三个方法都是预定义的JavaScript方法,通过指定对象方法的上下文(this),从而使别的对象也能使用自己定义的对象方法:

let person = {
    getOccup: function() {
        console.log(this.occupation);
    }
};
let student = {occupation:"student"}
let teacher = {occupation:"teacher"};

person.getOccup.call(student);    //student      
person.getOccup.apply(student);  //student
person.getOccup.bind(student)(); //student
person.getOccup.call(teacher);    //teacher      
person.getOccup.apply(teacher);  //teacher
person.getOccup.bind(teacher)(); //teacher

其中 bind 方法返回一个函数,必须调用它才能执行代码。

差别

它们之间的差别体现在传参上。

call()、apply() 、 bind() 这三个函数的第一个参数都是 this 的指向对象,其余参数是对象方法所需的参数,差别体现在此处:

call() 分别接收参数,参数间逗号隔开,

apply() 通过数组的形式接收参数,

bind() 和 call() 一样,分别接收参数。

let person = {
    intro: function(name, age) {
         console.log(name + " is " + age + " years old and a " + this.occupation);
    }
};
let teacher = {occupation:"teacher"};
person.intro.call(teacher, "Jack", 50);    //Jack is 50 years old and a teacher
person.intro.apply(teacher, ["Jack", 50]);  //Jack is 50 years old and a teacher
person.intro.bind(teacher, "Jack", 50)(); //Jack is 50 years old and a teacher

person.intro.call(teacher, ["Jack", 50]); //Jack,50 is undefined years old and a teacher

/*
person.intro.apply(teacher, "Jack", 50);
报错:Uncaught TypeError: CreateListFromArrayLike called on non-object
*/

应用

JavaScript 数组没有 max() 方法,但我们可以应用 Math.max() 方法来模拟。

// Math.max() 方法找到(数字列表中的)最大数字:
Max.math(1, 2, 3); //返回 3

//在数组上模拟 max 方法
let arr = [2, 1, 3];
Max.math.apply(null, arr); //返回 3

标签:bind,JavaScript,50,person,call,Jack,apply,teacher
来源: https://www.cnblogs.com/hzyuan/p/15901862.html