读书人

怎么理解方法中的this

发布时间: 2012-03-26 15:46:56 作者: rapoo

如何理解方法中的this?
比如下面的程序:

JScript code
function classA(){    this.x = 0;    this.show = function(){        alert(this.x);    }    this.show();}new classA();


这里应该如何理解show()函数中的this呢?我感觉可以有两种解释
1.show()是一个闭包,所以show()中的this是直接使用了外部classA()函数的this。此时,两个this是同一个变量。
2.show()函数被调用时会隐含传递一个调用它的对象的引用,也就是this,所以show()中的this只是和外部的this的值相同,担不是同一个变量。(Java中就是这种)

应该是那种解释呢?

[解决办法]
只是传递一个引用
JScript code
            x = 1;            function classA(){                this.x = 0;                this.show = function(){                    alert(this.x);                }                this._show = function(){                    this.show.call(window);                }                this._show();            }            var a = new classA(); 

读书人网 >JavaScript

热点推荐