一、this出现的几种情况
1、构造函数中的this
function Fn(){
console.log(this);
}
var obj1 = new Fn(); //obj1, 函数Fn中的this指向实例对象obj1
2、普通函数中的this
function Fn1(){
console.log(this);
}
Fn1(); //window, Fn1属于window全局对象的一个属性,即:Fn1()===window.Fn1(),函数Fn1中的this指向window对象
Fn()===window.Fn(); //window, Fn属于window全局对象的一个属性,即:Fn()===window.Fn(),函数Fn中的this指向window对象
3、对象中的this
var obj = {
that: this,
fn: function(){
console.log(this);
}
}
console.log(obj.that); //window, this不存在Object对象中的,this指向window全局对象
obj.fn(); //obj, this指向调用其所在函数的对象
二、总结:
1、this不存在Object对象中的,它只存在一个Function类型的函数中
2、this指向使用new操作符实例化其所在函数的实例对象
3、this还指向调用其所在函数的对象
三、误区:
1、注意在全局函数中的this
var obj = {
fn: function(){
function test(){
console.log(this);
}
test();
}
}
obj.fn(); //window, test属于window对象的属性,因此this指向的是window对象,而不是obj对象
2、上面的例子中,this一般被误认为obj对象,其实不是的,它指向window全局对象,但可以通过obj中的一个局部变量来指向obj
var obj = {
fn: function(){
var self = this;
function test(){
console.log(self); //用self来指向obj对象
}
test();
}
}
obj.fn(); //obj
3、方法的赋值表达式
var obj = {
prototype: "value",
fn: function(){
var self = this;
function test(){
console.log(this.prototype); //undefined,this指向window对象
console.log(self.prototype); //value,用self来指向obj对象
}
test();
}
}
obj.fn();
var fn = obj.fn;
fn(); //输出两个undefined,this指向window对象, 上一句中变量fn是window对象的一个属性,此时的self变量保存的还是window对象
综上:this总是指向其所在函数类型的对象以及调用其所在函数中的(顶层)对象.