あなたが何をしようとしているのかわからないが、これを試してみてください:
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();