this指针与function变量--this究竟指向哪里?

时间:2023-03-09 05:43:37
this指针与function变量--this究竟指向哪里?

参考文章:《深入浅出 JavaScript 中的 this》 http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/

JavaScript的this指针为何如此让人琢磨不透、难于理解?这个问题研究了很久,总算有些眉目了。这个问题源于JavaScript是顺序执行的,是解释执行的,运行时才能动态绑定this指针。这区别于Java、C#等语言,它他们都编译后执行的,this指向当前的对象。

1.function类型变量

javascript中的function也可理解为一种数据类型,通过function来定义函数(方法)。

function hello() { }
alert(typeof(hello)); //输出function

this引用的对象究竟是什么?this指针指向一个对象,并且与function变量密不可分。要了解this指针的指向,需要先了解function变量是如何定义的。

2.function中的成员定义

function中可以定义三类:私有成员(var变量)、公有成员(this)和window对象成员。

   function Person() {
var age = 30;
this.name = "Bass";
income = 0;
}
//age //私有成员,不能在Person之外调用
//name //公有成员,需要通过Person类对象调用
var p = new Person();
alert(p.name);
//income //window对象成员,可以直接或通过window对象调用
income = 10000000;
window.income = window.income * 10;
alert(income);

3.this指针的指向

1) function变量作为对象方法被调用,此时this指针指向对象本身。

   var obj = {
hello: function (param) {
return (this == param)
}
}
alert(obj.hello(obj)); //输出true

2) function变量作为普通函数被调用,此时this指针指向window对象。

    function hello(param) {
return (this == param);
}
alert(hello(window)); //输出true
//window.hello(window); //2)可以理解为1)的特情况,2)定义的函数默认是定义在window对象的作用域内的,默认是window对象的方法。

3) function变量作为构造函数被调用,此时this指针指向新创建的类对象。

    function HelloWorld() { //为区别JavaScript类和普通JavaScript方法,HelloWorld首字母大写
this.hello = function (param) { //hello方法是定义在HelloWorld类中的,只能定义类实现,才能调用该方法
return (this == param);
}
} var obj = new HelloWorld();
alert(obj.hello(obj)); //输出true

4) function变量作为prototype方法被调用,此时this指针指向调用function的对象(新创建的类对象或prototype对象)。

prototype对象方法,是对拥有prototype对象的类的方法扩展,方法可视为是类的公有成员方法。

    function HelloWorld() { }
HelloWorld.prototype.hello = function (param) {
return (this == param);
}
alert(HelloWorld.prototype.hello(HelloWorld.prototype)); //输出true
var obj = new HelloWorld();
alert(obj.hello(obj)); //输出true
alert(obj == HelloWorld.prototype); //输出false

5) function变量调用call或apply方法来执行,此时this指针指向被改变,并指向call或apply方法的第一个参数所引用的对象。

    function HelloWorld() {
this.hello = function (param) {
alert(this == param);
}
}
var t1 = new HelloWorld();
var t2 = new Object();
t1.hello(t1); //输出true //直接调用方法,this指向不改变
t1.hello.call(t2, t1); //输出false //通过call方法调用,this指向改变,并指对象t2
t1.hello.call(t2, t2); //true

6) function变量作为html元素的事件处理方法被调用,此时this指针指向触法事件的元素本身 ,并可作为实参传入事件处理方法。

不太明白以下的测试结果,谁知道告诉我一下。

    <div onclick="hello(this)">
HelloWorld
</div>
    function hello(param) {
alert(this == param); //true
alert(this.innerText); //undefined
alert(this == window); //true
alert(param == window); //false
alert(param.innerText); //HelloWorld
alert(this.innerText); //undefined
}

以上就是我的测试验证结果,6)的结果不太明白为什么,我觉得this指向window还能理解,为什么this又等于param是为什么呢。麻烦知道的同鞋告诉我一下为什么?