ITPub博客

首页 > IT职业 > IT生活 > 第 38 题:apply、call 和 bind 是什么?哪些区别?

第 38 题:apply、call 和 bind 是什么?哪些区别?

IT生活 作者:wyfem 时间:2021-09-09 08:51:28 0 删除 编辑

三者都是改变 this 指向的 api

用法

apply:xxx.apply(this, [arg1, arg2])

call:xxx.call(this, arg1, arg2)

bind:xxx.bind(this, arg1, arg2)

区别

主要是传参方式和执行方式不同

  • apply、call 的区别:接受参数的方式不一样

  • bind:不立即执行。而 apply、call 立即执行

栗子

初始状态

let Person = function(name, age) {
    this.name = name;
    this.age = age;
};

let Student = function() {
    this.class = 'classA';

    this.run = function() {
        console.log(this);
    };
};

let student = new Student();

student.run();

图片描述

可以看见这个时候打印的 this 是指向 Student 构造函数,并且和 Person 构造函数没有任何关联

使用 apply 改变 this 指向

let Person = function(name, age) {
    this.name = name;
    this.age = age;
};

let Student = function() {
    this.class = 'classA';

    this.run = function() {
        Person.apply(this, ['xiaoming', 20]);
        console.log(this);
    };
};

let student = new Student();

student.run();

图片描述

这个时候 this 已经指向了 Person 构造函数了

使用 call 改变 this 指向

let Person = function(name, age) {
    this.name = name;
    this.age = age;
};

let Student = function() {
    this.class = 'classA';

    this.run = function() {
        Person.call(this, 'xiaoming', 20);
        console.log(this);
    };
};

let student = new Student();

student.run();

图片描述

这个时候 this 已经指向了 Person 构造函数了

使用 bind 改变 this 指向

let ex = '';

let Person = function(name, age) {
    this.name = name;
    this.age = age;
};

let Student = function() {
    this.class = 'classA';

    this.run = function() {
        ex = Person.bind(this, 'xiaoming', 20);
        console.log(this);
    };
};

let student = new Student();

student.run();
ex();

图片描述

使用 bind 的话,需要执行了 this 改变才会生效

总结:使用 apply、call 和 bind 确实可以改变 this 指向,但是原有对象的属性也跟着一起过去了

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2894/viewspace-2797333/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-12-22

  • 博文量
    73
  • 访问量
    33676