call, apply,bind改变this指向方法

call,  apply,bind都可以改变this指向

区别

call只能一个参数一个参数的传入。

apply则只支持传入一个数组

至于bind方法,他是直接改变这个函数的this指向并且返回一个新的函数,之后再次调用这个函数的时候this都是指向bind绑定的第一个参数。bind传餐方式跟call方法一致。

列子:

<script>
    //比方说张三的中饭有红烧鱼 李四的中饭有基围虾
    const person1 = {
        name: '张三',
        eat(...args) { //...args不限参数
            console.log(this.name + '吃张三的红烧鱼   和自己的' + [...args]);
        },
    }

    const person2 = {
        name: '李四',
        eat(...args) {
            console.log(this.name + '吃李四的基围虾    和自己的' + [...args]);
        },
    }

    person1.eat.call(person2, '白菜', '黄瓜') // 李四想吃张三的红烧鱼
    person2.eat.call(person1, '白菜', '黄瓜') // 张三也想吃李四的红烧鱼

    person1.eat.apply(person2, ['白菜', '黄瓜'])
    person2.eat.apply(person1, ['白菜', '黄瓜'])


    const test1 = person1.eat.bind(person2, '白菜', '黄瓜')
    const test2 = person2.eat.bind(person1, '白菜', '黄瓜')
    test1()
    test2()
</script>
<script>
    function Student(name, sex, age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }


    function GradStudent(name, sex, age, course) {
        // Student.call(this, name, sex, age)
        Student.apply(this, [name, sex, age])
        this.course = course
    }

    var student = new Student('学生1', '女', '12');
    var grastudent = new GradStudent('学生2', '男', '18', '英文');

    console.log(student)
    console.log(grastudent)
</script>

总结一些,使用这种方法呢 ,改变this指向已达一个对象复用另一个对象里的方法

猜你喜欢

转载自blog.csdn.net/Candy_mi/article/details/87628953