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

2022/2/16 20:11:43

本文主要是介绍【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


这篇关于【JavaScript】call()、apply()、bind()的用法和区别的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程