一、call( )函数
call()函数有两个作用:
1.函数调用
2.改变this指向
1)在使用call方法来进行this指向改变的同时,立即执行该函数
2)当需要传递参数的时候,call方法将参数依次传递进去(参数以列表的形式)
const student = {
name: 'student'
}
const person = {
name: 'person',
introduce(age, gender) {
console.log(`${this.name}今年${age}岁,性别是${gender}`);
// student 今年33岁,性别是男
}
}
//本身student没有introduce的方法.通过this指向的改变,来借用person对象中的introduce方法
person.introduce.call(student, 33, '男');
二、apply( )函数
apply( )函数有两个作用:
1.调用函数
2.改变this指向
1)在使用apply方法来进行this指向改变的同时,立即执行该函数。
2)当需要传递参数的时,applay方法需要将所有的参数放在同一个数组中进行传递。
const student = {
name: 'student'
}
const person = {
name: 'person',
introduce(age, gender) {
console.log(`${this.name}今年${age}岁,性别是${gender}`);
// student 今年22岁,性别是女
}
}
//本身student没有introduce的方法.通过this指向的改变,来借用person对象中的introduce方法
person.introduce.apply(student, [22, '女']);
三、bind( )函数
1.在改变函数 this 指向的时候,返回一个被改变的新函数,需要手动重新调用后再执行。
2.当需要传递参数时,bind 方法直接从返回的新函数中传递即可。
3.bind()改变this指向,只能生效一次。
let person={
name:'person',
introduce(age,sex){
console.log(`${this.name}今年${age}岁,性别是${sex}`);
// teacher今年45岁,性别是男
}
}
let teacher={
name:'teacher'
}
let newIntroduce=person.introduce.bind(teacher);
//手动调用 才能执行
newIntroduce(45,"男");