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
我们知道,函数既可以当作一个对象的方法来调用,也可以独立调用。当它作为一个对象的方法时,显而易见,它指向的是调用它的对象。但是当它独立调用呢?给出一个例子:
- var flight={
- airline:"Oceanic",
- number:815,
- 'first-name':'hu',
- departure:{
- IATA:"SYD",
- time:"2004-09-22 14:25",
- city:"Sydney"
- }
- }
- flight.double=function(){
- var that=this;
- var helper=function(){
- alert(that==this);
- }
- helper();
- }
- flight.double();
首先我把外层函数的this赋给that,然后在内层函数中将this关键字与that做全等号比较,结果弹出一个打打的false!蛋疼,内层函数中this并没有绑定到外层函数的this,那么它绑定的是什么呢?好,修改一下代码:
- flight.double=function(){
- var that=this;
- var helper=function(){
- alert(window==this);
- }
- helper();
- }
- flight.double();
将this与window做全等,这时候再运行,发现弹出的是true。由此得出结论,当函数独立调用时(这里所属的独立是它既不属于对象的方法,也不是用new来调用),它绑定到的是全局对象。这时候,为了使用外层函数中的this,例子中已经演示,可以在外层函数作用域中定义一个that变量,然后将this的引用赋给它,在内层函数中,可以使用that来访问。