目前只接触到了几种 总结一下
定义在全局的函数 this指向window
console.log(this);//window
function abc(){
console.log(this);//window
}
对象中的方法 this指向这个对象
在对象属性中,this指向外层的this,因为在描述属性的时候这个时候对象还没有生成。
对象的方法中this是该对象本身,因为当调用方法时,对象已经生成了。
var a = 10;
var obj1 = {
a: 100,
c: this.a, // 10 这里的this指向window
init: function () {
console.log(this.a) // 100 这里的this指向obj1
}
}
var a = 10;
var obj1 = {
a: 100,
c: this.a, // 10 属性描述 这里的this指向window
init: function () {
var obj = {
a: 1,
c: this.a, // 100 this obj1
b: function () {
console.log(this.a); // 1 方法里的this指向调用他的方法 obj
}
}
return obj;
}
}
回调函数中的this 指向window
var obj = {
a: function () {
console.log(this); // this指向obj
var arr=[1,2,3];
arr.forEach(function(){
console.log(this); // 这里是forEach的回调函数 this指向window
})
},
}
obj.a();
var obj = {
b: function (fn) {
fn();
console.log(this, "_____"); //obj
},
c: function () {
console.log(this); //window
}
}
obj.b(obj.c); // c为回调函数
事件监听中的回调函数 this指向被监听的对象
document.addEventListener("click",clickHandler);
function clickHandler(e){
console.log(this) // document e.currentTarget
}
箭头函数 this指向外层的this
var obj = {
a: function () {
var arr = [1, 2, 3, 4, 5, 6]
arr.forEach(function () {
console.log(this) // 这里的this是window
})
},
b: function () {
var arr = [6, 5, 4, 1, 2, 3]
arr.forEach(item => {
console.log(this) // 这里是obj对象
})
}
}
obj.a()
obj.b()
未完待续