1 全局函数
alert(this);//[object, Window]
2
function test(){
alert(this);
};
//undefined
3 对象中的方法
var obj = {
name: 'obj对象',
test: function()
{
alert(this); //object Object
alert(this.name); //obj对象
}
};
obj.test();
结论: js中this永远指向属性或方法所属的对象
4 闭包中this
闭包函数属于全局
4.1
var name = 'this指向window对象';
var obj = {
test: function()
{
return function(){
return this.name;
};
}
};
alert(obj.test()); //function(){return this.name};
alert(obj.test()()); //this指向window对象
4.2 _this代替this
var name = 'this指向window对象';
var obj = {
name: '_this指向局域变量',
test: function()
{
var _this = this;
return function(){
return _this.name;
};
}
};
alert(obj.test()()); //_this指向局域变量