this的指向问题
1-对象打点调用函数 this指向对象
情况1:如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window,但是我们这里不探讨严格版的问题,你想了解可以自行上网查找。
情况2:如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
情况3:如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象,
let yunmu = {
nickname: "daitou",
age: 12,
sayHello: function () {
console.log("我是" + this.nickname + ",我" + this.age + "岁了");
console.log(window === this);
},
};
//对象打点调用函数 this指向对象
daitou.sayHello();
2-圆括号直接调用函数,则函数的上下文是window对象
function fun() {
return this.a + this.b;
}
var a = 1;
var b = 2;
let obj = {
a: 3,
b: fun(),//圆括号调用函数,this指向window b:3,
fun: fun,
};
let result = obj.fun();
console.log(result); //6
3-数组(类数组对象)枚举出函数进行调用,上下文是这个数组(类数组对象)
let arr = [
"A",
"B",
"C",
function () {
console.log(this[0]);
},
];
arr[3]();//"A"
4-IIFE函数,this指向是window对象
var a = 1;
var obj = {
a: 2,
fun: (function () {
console.log(this);//window
var a = this.a;
return function () {
console.log(this);//object
console.log(a + this.a); //3
};
})(), //iife
};
obj.fun(); //对象打点调用
5-定时器、延时器调用函数,this指向window
setInterval(function(){
console.log(this === window);//true
},1000)
let obj = {
a: 1,
b: 2,
fun: function () {
console.log(this.a + this.b);
},
};
var a = 3;
var b = 4;
setTimeout(
function () {
obj.fun(); //3
let c=this.a+this.b;
console.log(c);//7
},
2000
);
6-事件处理函数,this指向绑定事件的DOM元素
DOM.onclick = function(){
this ===dom元素
}
7-当this碰到return时,如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例。
function fn() {
this.user = 'daitou';
return {
user:1,
};
}
var a = new fn;
console.log(a.user); //1
function fn() {
this.user = 'daitou';
return {};
}
var a = new fn;
console.log(a.user); //undefined
function fn() {
this.user = 'daitou';
return function();
}
var a = new fn;
console.log(a.user); //undefined
function fn() {
this.user = 'daitou';
return undefined;
}
var a = new fn;
console.log(a.user); //daitou