Javascript中的类和范围

Jin*_*iel 5 javascript scope class

我在Javascript中编写了以下代码.

function main()
{
    this.a ;
    this.set = function()
    {
        a = 1;
    }
}

var l = new main();

alert("Initial value of a is "+ l.a );
l.set();
alert("after calling set() value of a is   "+ l.a );
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我得到a的值为未定义.为什么即使在我调用set()之后未定义?

ale*_*lex 7

你需要参考a使用this.a.

否则,您指的是一个局部变量a(如果您使用过var,省略它已awindow对象上创建了一个属性,本质上是一个全局变量)而不是对象的属性a(this将绑定到新创建的对象).

jsFiddle.


ter*_*ško 2

到 JavaScript 中:

function main()
{
    this.a ;
    this.set = function()
    {
        a = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

将看起来像

function main();

{ // starts unattached object literal
    this.a ;
    this.set = function();

    { // starts another unattached object literal 
        a = 1; // sets value to   window.a
    }
}
Run Code Online (Sandbox Code Playgroud)