this 的情况说明
this的几种情况说明
我们研究的 this 都是研究函数私有上下文中的 this
因为全局上下文中的 this -> window
块级上下文中没有自己的 this , 在此上下文中遇到的 this ,都是其所处环境(上级上下文)中的 this
ES6 中的箭头函数和块级上下文类似,也是没有自己的 this ,遇到的 this 也是其上级上下文中的
this 是执行主体: 通俗来说,是谁把他执行的,而不是在哪执行的,也不是在哪定义的,
所以 this 是谁和在哪执行以及在哪定义都没有直接的关系,想搞定 this ,我们可以按照以下总结的规律去分析
THIS 指向的规律:
@1 给 DOM 元素进行事件绑定(不论DOM0 还是 DOM2),当事件行为触发,绑定的方法执行,方法中的 this 是当前 DOM 元素本身
@2 当方法执行,我们看函数前面是否有“点”
- 有, “点” 之前是谁, this 就是谁
- 没有,this就是window(非严格模式),或者 undefined (严格模式)
- 匿名函数,自执行函数,回调函数中的 this ,一般都是 window/undefined 除非做过特殊处理
回调函数:把一个函数作为实参值,传递给另外一个函数(在另外一个函数中把其执行)
const fn = function (callback) {
callback();
}
fn(function(){})
定时器,匿名函数 this -> window (严格模式下是 undefined)
setTimeout(function () {
console.log(this); //window
}, 1000);
forEach([回调函数],[修改回调函数中的THIS])
let arr = [10, 20];
let obj = { name: 'huakaibubai' };
arr.forEach(function (item, index) {
// console.log(item, index);
console.log(this); //window/undefined
});
arr.forEach(function (item, index) {
console.log(this); //obj
}, obj); //forEach([回调函数],[修改回调函数中的THIS])
自执行函数中的 THIS 指向 window
// 自执行函数:创建完立即执行
(function(){})();
~function(){}();
!function(){}();
+function(){}();
(function (x) {
console.log(this); //window/undefined
})(10);
方法中没有点, THIS 指向window, 有 ‘点’ ,‘点’之前是谁,THIS 就指向谁
const fn = function () {
console.log(this);
};
let obj = {
name: 'huakaibubai',
// fn:fn
fn
};
fn(); //this->window/undefined
obj.fn(); //this->obj
DOM 元素绑定事件
给 DOM 元素绑定事件(不论 DOM0 还是 DOM2),当事件行为触发,绑定的方法执行,方法中的 THIS 是当前 DOM 元素本身
document.onclick = function () {
console.log(this); //document
};
document.addEventListener('click', function () {
console.log(this); //document
});
牛刀小试,请输出下面运行的结果
// let 和 var 是不一样的
var x = 3,
obj = { x: 5 };
obj.fn = (function () {
this.x *= ++x;
return function (y) {
this.x *= (++x) + y;
console.log(x);
}
})();
var fn = obj.fn;
obj.fn(6);
fn(4);
console.log(obj.x, x);