2013-03-03 126 views
2

这里是我的代码:范围以JavaScript对象

var Test = (function() { 
    function Test() { 
     this.sum = n; 

     this.calculate(); 
    } 

    Test.prototype.calculate = function() { 
     n = 5; 
     return n; 
    } 
    return Test; 
})(); 

var mytest = new Test(); 

能否请您解释一下为什么n是不确定的?我认为回来应该有所帮助,但我错了。

+0

'N' *是* 5调用'calculate'后,只有你之前得到一个例外。看看你的错误控制台。 – Bergi 2013-03-03 12:53:39

+0

你想做什么?你什么时候认为'n'是5,应该返回'n'?你是如何测试它的? – Bergi 2013-03-03 12:55:02

回答

0

不知道你正在尝试做的,但试试这个:

var Test = (function() { 
    function Test() { 
     this.sum = this.calculate(); 
    } 

    Test.prototype.calculate = function() { 
     var n = 5; 
     return n; 
    } 
    return Test; 
})(); 

var mytest = new Test(); 
alert(mytest.sum); // 5 

要回答你的问题 - nundefined,因为它有,当你试图做this.sum = n;没有价值。如果你第一次调用this.calculate(),然后尝试分配this.sum = n;,它可能会奏效。但即使在这种情况下,这是非常错误的,因为你将变量n泄漏到全局命名空间中(当你没有明确地初始化变量var时,它泄漏到全局命名空间 - window)。所以说明我的意思 - 这可能会起作用:

var Test = (function() { 
    function Test() { 
     this.calculate(); 

     this.sum = n; // n is global now, hence accessible anywhere and is defined by this moment 
    } 

    Test.prototype.calculate = function() { 
     n = 5; // not initialized with var so it leaks to global scope - gets accessible through window.n 
     return n; // has no sense, since you do not use returned value anywhere 
    } 
    return Test; 
})(); 

var mytest = new Test(); 
2

您的构造函数似乎有一个错误。在分配之前,您正在从n读取。

这也许会更清晰:

function Test() { this.sum = this.calculate(); } 

然后得到完全摆脱n价值。

Test.prototype.calculate = function() { return 5; } 
0

这里我试着解释一下。

function Test() { 
    this.sum = n; // assign undefined to this.sum 

    this.calculate(); // n = 5, but doesn't affect this.sum as undefined is already passed to sum 
} 

正确的行为(你想要的)

function Test() { 

    this.calculate(); 
    this.sum = n; 

}