call()、apply()bind()的作用与区别

简介

每个函数都包含两个非继承而来的方法:apply()call()
callapply都属于Function.prototype的一个方法,所以每个function实例都有callapply属性;

作用

它们共同的作用:callapplybind 都是用来修改函数中this的指向问题;

区别

call():第一个参数是this的指向,没有参数默认指向window。在使用call()方法时,传递给函数的参数必须逐个列举出来。(不会产生新的函数,只是在调用时,绑定一下而已)

apply():第一个参数是this的指向,没有参数默认指向window。在使用apply()方法时,传递给函数的是参数数组。(就参数和call不一样其他都一样,不会产生新的函数,只是在调用时,绑定一下而已)

bind():第一个参数是this的指向,没有参数默认指向window。在使用call()方法时,传递给函数的参数必须逐个列举出来。(语法和call一模一样,区别在于立即执行还是等待执行,bind会产生新的函数,bind不兼容IE6~8)

代码举例

var name = 'Evan';
var age = 20;
var person = {
    name: 'Hillary',
    age: 19,
    sayIntroduce: function () {
        return "Hello, My name is " + this.name + " and I'm " + this.age + ' years old.'
    },
    sayHobby: function (val1, val2) {
        return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
    }
}
var person1 = {
    name: 'Coy'
}
console.log(person.sayIntroduce()); // Hello, My name is Hillary and I'm 19 years old.

当我们通过 callapply 来改变this的指向时,不传任何参数,则默认为将this指向修改为 windows

 // 当没有参数时,默认将this指向 window
 console.log(person.sayIntroduce.call()); // Hello, My name is Evan and I'm 20 years old.
 console.log(person.sayIntroduce.apply()); // Hello, My name is Evan and I'm 20 years old.

有参数时,this 指向第一个参数:

// 将this指向 person1,由于person1中没有age属性,因此为 undefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Coy and I'm undefined years old.
console.log(person.sayIntroduce.apply(person1)); // Hello, My name is Coy and I'm undefined years old.

当需要传递参数时,call可以直接写多个参数,apply需要用数组方式传递:

console.log(person.sayHobby.call(person1, 'swimming', 'hiking')); // I'm Coy, I like swimming and hiking.
console.log(person.sayHobby.apply(person1, ['swimming', 'hiking'])); // I'm Coy, I like swimming and hiking.

bind()不是立即执行

person.sayHobby.call(person1, 1, 2); // 改变sayHobby中的this,并且把sayHobby立即执行
person.sayHobby.bind(person1, 1, 2); // 改变sayHobby中的this,sayHobby并不执行

bind会把sayHobby中的this预处理为person1,此时sayHobby没有执行,当点击的时候才会把sayHobby执行

document.onclick = person.sayHobby.bind(person1);

下面是一个构造函数的例子:

//构造函数应用
function Grade(max, min, average) {
    this.max = max;
    this.min = min;
    this.average = average;
}
 
function Subject(subjectName,max, min, average) {
    Grade.call(this, max, min, average);
    this.subjectName = subjectName;
}
var math = new Subject('math', 99, 60, 80);
console.log(math);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值