这是我的代码:
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 :(得分:2)
你的构造函数似乎有一个bug。在分配之前,您正在阅读n
。
也许这会更清楚:
function Test() { this.sum = this.calculate(); }
然后完全摆脱n
值。
Test.prototype.calculate = function() { return 5; }
答案 1 :(得分: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
要回答您的问题,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();
答案 2 :(得分: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;
}