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)); 

在这里插入图片描述

你可能感兴趣的:(js,javascript)