日期:2014-05-16  浏览次数:20334 次

JAVASCRTPT权威指南第五版,函数一章的疑惑,请高人指点
当一个函数作为函数而不是方法调用的时候,这个this关键字引用全局对象。容易令人混淆的是,当一个嵌套的函数(作为函数)在一个包含的函数之中调用,而这个包含的函数是作为方法调用的,这也是成立的:this关键字在包含的函数中有一个值,但它却(不太直观)引用嵌套的函数体的内部的全局对象。

-------------------------------------------------------------------------------
以上是JAVASCRTPT权威指南第五版,函数一章中的一段话,是机械工业出版社翻译的中文。下面是对应的英文原版。

怎么也看不懂它要讲什么,谁能举个简单的代码例子说明一下?
-------------------------------------------------------------------------------

When a function is invoked as a function rather that as a method, the this keyword refers to the global object. Confusingly, this is true even when a nested function is invoked (as a function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but (counterintuitively) refers to the global object within the body of the nested function.

------解决方案--------------------
先说一下什么是函数什么是方法
函数指的是实现了某特定功能的代码的集合
方法指的是某对象的某种行为,虽然也是代码的集合,但带有一定的含义.
函数:
function chkForm(frm){ ... }
方法:
var computer = {};
computer.start = function (){ startQQ(); startMSN();startTaskPlan(); }

当一个函数(这个函数指的是function(){}这样的东西)作为函数运行的时候:
function test(){
this.alert("这里的this是全局对象,在浏览器里就是window对象");
}
而在嵌套的方法里:
function test(){
this.name="test";
return function intest(){
var name = "intest";
alert(this.name);
}
}
test()();
可以看到this.name值是:test

一个简单的判断方法是:this总是指向命名空间栈里最上层的命名空间.(注:这句是我说的,我也在考虑正确性)
函数不是命名空间,对象和类是
如:function Girl(name){ this.age = 18; this.weight = 45;this.name = name;} new Girl("julia");
var namespace = new Object();
namespace.name = "dragComponent";
namespace.getName = function(){ return this.name};
------解决方案--------------------
我觉得权威指南里面是说的比较绕口和令人费解。其实可以把上面所说的函数当作window对象的方法来理解。
而this关键字总是指向当前对象。在上面所说的“不作为一个方法”来调用的时候,可以理解为调用的是window
对象的方法,这样this是指向当前对象window的,所以也是全局性的,这样就跟“作为对象的方法来调用”的时候,
this指向当前对象,在思想上一致了,容易理解的多。
例如:
function test(){
this.alert('test');
}
test();等同于window.test();

var test = {
property:'123',
method:function(){
return this.property;
}
}
test.method();返回123