this、call、apply、bind

2019-10-22  本文已影响0人  人间四月天i

this的指向(this永远指向最后调用它的那个对象)

改变this指向

//箭头函数   前
var name="window"
var a={
    name:"hello",
    fun1:function(){
        console.log(this.name)
    },
    fun2:function(){
        setTimeout(function(){
            this.fun1()
        },1500)
    }
}
a.fun2()     // this.fun1 is not a function
//后
var name="window"
var a={
    name:"hello",
    fun1:function(){
        console.log(this.name)
    },
    fun2:function(){
        setTimeout(()=>{      //  或者 var _this=this
            this.fun1()
        },1000)
    }
}
a.fun2()
//apply   fun.apply(thisArg,[argsArray])
var a ={
  name : "lili",
  fn : function (a,b) {
   console.log( a + b)
  }
 }
 var b = a.fn;
 b.apply(a,[1,2])  // 3
 
var a={
    name:"hello world!",
    fun1:function(){
        console.log(this.name)
    },
    fun2:function(){
        setTimeout(function(){
        this.fun1()
        }.apply(a),1000)
    }
}
a.fun2()     // hello world!
//call   fun.call(thisArg[,arg1[,arg2[,...]]])
var a ={
  name : "lili",
  fn : function (a,b) {
   console.log( a + b)
  }
 }
 var b = a.fn;
 b.call(a,1,2)  // 3
 
var a={
    name:"hello world!",
    fun1:function(){
        console.log(this.name)
    },
    fun2:function(){
        setTimeout(function(){
            this.fun1()
        }.call(a),1000)
    }
}
a.fun2()     // hello world!
//bind
var a ={
  name : "lili",
  fn : function (a,b) {
   console.log( a + b)
  }
 }
 var b = a.fn;
 b.bind(a,1,2)()   // 3
 
var a={
    name:"hello world!",
    fun1:function(){
        console.log(this.name)
    },
    fun2:function(){
        setTimeout(function(){
            this.fun1()
        }.bind(a)(),1000)
    }
}
a.fun2()    // hello world!
上一篇 下一篇

猜你喜欢

热点阅读