this的指向(this永远指向最后调用它的那个对象)
改变this指向
- ES6函数箭头
- 在函数内部使用 var _this=this
- 使用call、apply、bind
- new实例化一个对象
- apply
- bind 接收多个参数
- call
//箭头函数 前
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!
网友评论