this的概述以及指向问题
-
一. this的概述
- this是每次调用函数的时候都会向函数内部传递的一个隐含的参数;
- this指向是一个对象,函数执行的上下文对象;
- 函数的调用方式不同,this的指向也会不同;
- this指向是函数的执行者;
- Es6中箭头函数的this指向是继承外部的环境,只受外部环境的变化而变化;
-
二. this的作用
- 调用本类中的方法;
- 表示类中的属性;
- 可以使用this来调用本类的构造函数;
- this的指向表示当前的对象;
-
三. this的指向问题
-
作为普通函数直接调用
- 非严格模式:this指向window;
- 严格模式:this指向underfined;
-
作为事件处理函数
- this是绑定事件的那个元素(事件源);
-
作为对象的方法调用
- this指向调用该方法的对象;
-
作为自执行函数
- 非严格模式:this指向window;
- 严格模式:this指向underfined;
-
实例中的this指向实例对象
-
定时函数中的this指向window
四.this的使用场合 (this只应该出现在以下几种场合中)
-
函数是一个构造函数:
该函数的名字一大写字母开头
该函数被赋值给一个以大写字母开头的变量
该函数是一个ECMAscript6类构造函数
-
函数是一个方法:
该函数在对象字面量上
该函数被赋值给一个属性
该函数是一个ECMAscript6类的方法,getter或setter(除静态方法)
-
允许在以下函数中出现this关键字:
调用了该函数的 call() / apply() / bind() 方法
如果给出 thisAry:该函数是数组方法的一个回调(比如:.forEach() )
函数在 JS Doc 注释标记中有 @this 标签
其他情况被认为是有问题的,出现除此之外的this指向方法,系统将会报错
四.this的使用示例
function Foo(){
this.age = 12;
baz(()=>this)
}
class Foo {
constructor(){
this.age = 12;
}
foo() {
this.age = 14;
}
}
const obj = {
foo(){
this.age = 12;
}
}
const obj = {
get foo(){
return this.age;
},
set foo(val){
return this.age = val;
},
};
Object.defineProperty(obj , 'foo' , {
value:function foo(){
this.age = 12;
}
})
function Foo(){
this.foo = function foo(){
this.age = 12;
baz( ()=>this );
}
}
Foo.prototype.foo = function foo(){
this.age = 12;
}
const foo = function foo(){
this.age = 12;
}.bind(obj);
foo.forEach(function(){
this.age = 12;
baz(()=>this );
},thisAry)
function foo(){
this.age = 12;
}