JS——apply和call以及bind的区别

apply和call的区别

相同点: apply和call都是用来修改函数中this的指向。
不同点: 传参方式不同。
apply传给函数的参数合并为一个数组作为自己的一个参数。
call可以将传给函数的参数作为自己的参数。

举一个例子:

var name = 'Kevin';
var number = 7;
var person = {
    name: 'Curry',
    number: 30,
    sayIntroduce: function () {
        return "Hello, My name is " + this.name + " and my number is" + this.number
    },
    sayHobby: function (val1, val2) {
        return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
    }
}
var person1 = {
    name: 'Nash'
}
console.log(person.sayIntroduce()); // Hello, My name is Curry and my number is 30.

使用call和apply,不传参数,则默认将this指向为window

console.log(person.sayIntroduce.call()); // Hello, My name is Kevin and my number is 7.
console.log(person.sayIntroduce.apply()); // Hello, My name is Kevin and my number is 7.

传参数是,第一个参数为this的指向

// 将this指向 person1,由于person1中没有number属性,因此为 undefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Nash and my number is ndefined.
console.log(person.sayIntroduce.apply(person1)); // Hello, My name is Nash and my number is undefined.

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

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

再举一个构造函数的例子:

//构造函数应用
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为Subject
    this.subjectName = subjectName;
}
var math = new Subject('math', 99, 60, 80);
console.log(math);

在这里插入图片描述

bind

bind是将方法返回,也就是将方法给与给调用bind的对象。

var name = 'Kevin';
var number = 7;
var person = {
    name: 'Curry',
    number: 30,
    sayIntroduce: function () {
        return "Hello, My name is " + this.name + " and my number is" + this.number
    },
    sayHobby: function (val1, val2) {
        return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
    }
}
var person1 = {
    name: 'Nash'
}

var sayIntroduce= person.sayIntroduce.bind(person1); //返回的是方法
console.log(sayIntroduce()) //Hello, My name is Nash and my number isundefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Nash and my number is ndefined.
console.log(person.sayIntroduce.bind(person1)); 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值