关于this对象
this对象是在运行时基于函数的执行环境绑定的;
this大致分为四类
一、直接函数调用
在全局函数中,this等于window
const name = 'sun';
function getName() {
return this.name;
}
getName(); // sun
二、函数作为某个对象的方法调用时
this等于那个对象,匿名函数的执行环境具有全局性,因此this通常指向window,
const name = 'sun';
function getName() {
return this.name;
}
const obj = {
name:'lili',
getName,
}
obj.getName(); // lili
// 闭包中匿名函数
const name = 'sun';
const obj = {
name:'lili',
getName:function() {
return function() {
return this.name;
};
}
};
obj.getName()(); // 'sun'
三、构造函数
this指向构造函数实例化后的对象
function Person() {
this.name = 'li';
}
const person1 = new Person();
person1.name // li
四、是call和apply函数改变this指向
call 和 apply是函数的一个方法,作用是改变函数的调用对象。它的第一个参数就表示改变后的调用这个函数的对象。因此,这时this
指的就是这第一个参数。
const name = 'sun';
function getName() {
return this.name;
}
const obj = {
name:'lili',
getName,
}
obj.getName.apply(); // sun
当call 或 apply 的参数为空时,默认调用全局对象。因此,这时的运行结果为sun
,证明this
指的是全局对象。
如果把上面代码最后一行修改为
const name = 'sun';
function getName() {
return this.name;
}
const obj = {
name:'lili',
getName,
}
obj.getName.apply(obj); // lili