this:指的是你的函数执行时所在的环境(作用域)
函数this的指向(箭头函数除外):
谁调用函数,这个this就指向哪里
this的指向一般有四种情况:
- 全局作用域内调用函数,this就指向window
(function funn(){
console.log(this);//window;
}
- 通过事件来调用函数,this就指向这个事件的调用者
<button></button>
var btn = document.querySelector('button');
btn.addEventListener('click',function(){
console.log(this);//this
})
//如果使用箭头函数,会指向window
btn.addEventListener('click',()=>{
console.log(this);//window
})
- 对象调用其方法,this就指向这个对象
var obj={
name:"bgg神教,一统江湖",
skill:function(){
console.log(this);
}
}
obj.skill();//{name: "bgg神教,一统江湖", skill: ƒ}
- 通过构造函数来实例化的对象中的this,指向这个实例化对象
function Animal(name,type){
this.name=name;
}
var cat = new Animal('猫');
console.log(cat);//Animal {name: "猫"}
apply()
- 将obj1的this指向obj这个对象
语法:
call(obj,arg1,arg2,...);
obj1.skill.call(obj,arg1,arg2);
obj:表示你要将this重新指向到的新对象
arg1,arg2..:表示当做skill的参数传入
call()
- 将obj1的this指向obj这个对象
apply(obj,arr)
obj1.skill.apply(obj,arr);将obj1.的this指向obj这个对象;
obj:表示你要将this重新指向到新的对象
arr:表示数组或者类数组,数组里面的元素当做是skill的参数传入
call()和apply()的区别:第二个参数不一样
/*
* js可以通过call或apply方法来实现继承
*/
function Animal(name){
this.name=name;
this.skill=function(){
console.log(this.name);
}
}
function Cat(nm){
//构造函数里面的this是在实例化对象的时候才决定指向谁的
Animal.apply(this,[nm]);
}
var test=new Cat(['小猫']);
test.skill();
箭头函数
箭头函数本身是没有this,但我们用到this的时候,他会找定义函数时所处环境的this.
var btn = document.querySelector('.btn');
btn.addEventListener('click',function(){
setTimeout(()=>{
console.log(this);//btn
},1000)
})
setTimeout(()=>{
console.log(this);//window
},1000)
网友评论