Call、apply、bind的区别

Call、apply、bind的区别

基础

  var obj = {
            name: '小明',
            gender:"男",
            age: 18,
            say() {
                console.log(this.name+","+this.gender+"今年"+this.age)
            }
        }
        obj.say()//小明,男今年18
        var xh ={
            name:"小红",
            gender:"女",
            age:18
        }
        obj.say.call(xh)//小红,女今年18
		obj.say.apply(xh)//小红,女今年18
		obj.say.bind(xh)()//小红,女今年18

传参

    <script>
        var obj = {
            name: '小明',
            gender: "男",
            age: 18,
            say(shool, Grade) {
                console.log(this.name + "," + this.gender + "今年" + this.age + "在" + shool + "上" + Grade)
            }
        }
        var xh = {
            name: "小红",
            gender: "女",
            age: 18
        }
        obj.say.call(xh, "高等中学", "九年级")//小红,女今年18在高等中学上九年级
        obj.say.apply(xh, ["高等中学", "九年级"])//小红,女今年18在高等中学上九年级
        obj.say.bind(xh)("高等中学", "七年级")//小红,女今年18在高等中学上七年级
        obj.say.bind(xh, "高等中学", "九年级")()//小红,女今年18在高等中学上九年级
    </script>

总结

  • 语法
    • call:对象.call(要指的对象,"参数1","参数2")
    • apply:对象.apply(要指的对象,[参数1,参数2])
  • 相同点
    • 他们三者都是改变this的指向
    • 第一个参数都是this要指向的对象
    • 都可以后续传参
  • 不同点
    • call和apply都是对函数直接调用,bind方法返回的是一个函数需要()调用

    • call传递参数的时候是字符串对应传参,如:obj.say.call(xh, "高等中学", "九年级")

    • apply第二个参数是一个数组,如:obj.say.apply(xh, ["高等中学", "九年级"])

    • bind可以在调用处传参,如:obj.say.bind(xh)("高等中学", "七年级")

    • bind还可以向call一样传参,如:obj.say.bind(xh, "高等中学", "九年级")()