理解JavaScript中的this
2012-04-28 16:28
603 查看
一、this出现的几种情况
1、构造函数中的thisfunction 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、注意在全局函数中的thisvar 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总是指向其所在函数类型的对象以及调用其所在函数中的(顶层)对象.
相关文章推荐
- 深入理解javascript原型和闭包(10)——this
- 深入理解javascript之this
- 【原】理解javascript中的this
- JavaScript中关于this的理解
- 关于JavaScript中this的一些理解
- JavaScript中嵌套函数的this关键字的理解
- coffeescript(javascript) this 的理解
- 深入理解javascript关键字this
- 深入理解javascript原型和闭包(10)——this
- javascript--理解Javascript之this关键字
- js基础1-深入理解javascript之this
- 深入理解javascript原型和闭包(10)——this
- Javascript之this关键字的深入理解
- 对javascript的this理解
- Javascript中this、prototype、constructor的理解
- JavaScript 函数中的外部变量——理解 this
- 灵活的理解JavaScript中的this指向
- 深入理解Javascript之this关键字
- 准确理解javascript中的this的指向
- 深入理解javascript原型和闭包(10)——this