复习了下this指向,就如上一篇写过的用过[ ].slice.call()一样,需要弄明白this的指向
所有函数都有一个this,这个值是调用函数的当前对象
function Person(color){
console.log(this)
this.color=color;
this.getColor=function(){
console.log(this)
return this.color
};
this.setColor=function(color){
console.log(this)
this.color=color;
};
}
Person("red");
调用函数function的是window
function Person(color){
console.log(this)
this.color=color;
this.getColor=function(){
console.log(this)
return this.color
};
this.setColor=function(color){
console.log(this)
this.color=color;
};
}
var p=new Person("yellow");
// this是谁 是p,因为p指向这个对象
p.getColor();
// this是谁 p
person 是p对象调用的
function Person(color){
this.color=color;
this.getColor=function(){
console.log(this)
return this.color
};
this.setColor=function(color){
console.log(this)
this.color=color;
};
}
let p =new Person("yellow")
var obj={name:"哈哈"};
p.setColor.call(obj,"black");
// this是谁 obj
// this call强制改变this的指向
这里call强制改变this的指向,使他变成obj的调用
复习下改变this指向的call和apply函数
call()和apply()都是函数对象的方法,当调用函数call和apply方法都会调用这个函数,指定参数使其拥有其方法可以调用。
箭头函数this的指向
与普通函数的this指向是有区别的
箭头函数中,this的指向是父级程序的this指向
当前的程序,箭头函数的父级程序,没有this指向的就是window
let oDiv = document.getElementById('div')
oDiv.addEventListener('click' , ()=>{
console.log(this); //window
})
// 对li进行操作
const oLis = document.querySelectorAll('li');
oLis.forEach(function(item,key){
console.log(this); // 输出的是forEach的函数的this指向
// 箭头函数的this,是父级程序,forEach()的this,是window
item.addEventListener('click' , ()=>{
console.log(key,this);//0--4 window
})
})
在箭头函数中this的指向是指向父级的,所以调用forEach的是window对象
// forEach()中 函数的this指向,就是window
const arr = [1,2,3,4,5,6];
arr.forEach(function(){
console.log(this); //window
})
const obj = {
// 普通函数,this指向对象
fun1 : function(){console.log(this)},
// 箭头函数this指向是,父级程序
// 父级程序是对象
// 只有函数有this,obj对象没有this
// 父级程序没有this,指向的是window
fun2 : ()=>{console.log(this)},
// fun3是一个普通函数,this指向的是obj对象
fun3 : function(){
// fun4,是一个箭头函数,this指向的是父级程序的this指向
// 父级程序是fun3,fun3的this是对象,fun4箭头函数的this也是对象
const fun4 = ()=>{console.log(this)};
fun4();
}
}
obj.fun1(); //Object { fun1: fun1(), fun2: fun2(), fun3: fun3() }
obj.fun2(); //Window
obj.fun3(); //Object { fun1: fun1(), fun2: fun2(), fun3: fun3() }