面试题001-call/apply/bind

129 阅读1分钟

call/apply/bind三兄弟都是为了改变this指向,this指向:this 永远指向最后调用它的那个对象

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
        
        
        
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在高等中学上九年级

他们都是为了改变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, "高等中学", "九年级")() 原文链接