关于js this 的一个难点

本文探讨了 JavaScript 中 this 关键字的行为特性,特别是在不同作用域下 this 的指向变化,以及如何通过闭包来保持正确的 this 上下文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

到现在都还糊涂的一个问题: 
function outer(){ 
function inner(){ 
alert( this ); 
}(); 

Why "this" refer to the window object, the function inner is not the property of window.-_- 
猜想: 是不是当一个函数不作为其它对象的属性时,默认this引用window? 

猜想正确


this 
可 以简单概括为: "this" is a keyword not a property of any object, that refer to one object depending on the scope. In the global scope, it refers to the window object. In the function scope it refers to the object that has the function as its property. 

④蛋疼的this

我们知道,函数既可以当作一个对象的方法来调用,也可以独立调用。当它作为一个对象的方法时,显而易见,它指向的是调用它的对象。但是当它独立调用呢?给出一个例子:

  1.  var flight={  
  2.    airline:"Oceanic",  
  3. number:815,  
  4. 'first-name':'hu',  
  5. departure:{  
  6.   IATA:"SYD",  
  7.   time:"2004-09-22 14:25",  
  8.   city:"Sydney"  
  9. }  
  10.  }  
  11.  flight.double=function(){  
  12.    var that=this;  
  13.    var helper=function(){  
  14.    alert(that==this);  
  15. }  
  16. helper();  
  17.  }  
  18.  flight.double();  
 

首先我把外层函数的this赋给that,然后在内层函数中将this关键字与that做全等号比较,结果弹出一个打打的false!蛋疼,内层函数中this并没有绑定到外层函数的this,那么它绑定的是什么呢?好,修改一下代码:

  1.  flight.double=function(){  
  2.    var that=this;  
  3.    var helper=function(){  
  4.    alert(window==this);  
  5. }  
  6. helper();  
  7.  }  
  8.  flight.double();  
 

将this与window做全等,这时候再运行,发现弹出的是true。由此得出结论,当函数独立调用时(这里所属的独立是它既不属于对象的方法,也不是用new来调用),它绑定到的是全局对象。这时候,为了使用外层函数中的this,例子中已经演示,可以在外层函数作用域中定义一个that变量,然后将this的引用赋给它,在内层函数中,可以使用that来访问。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值