不知道你正在尝试做的,但试试这个:
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
要回答你的问题 - n
是undefined
,因为它有,当你试图做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();
'N' *是* 5调用'calculate'后,只有你之前得到一个例外。看看你的错误控制台。 – Bergi 2013-03-03 12:53:39
你想做什么?你什么时候认为'n'是5,应该返回'n'?你是如何测试它的? – Bergi 2013-03-03 12:55:02