Not sure what you are trying to do but try this:
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
To answer your question - n was undefined because it had no value when you were trying to do this.sum = n;. It could have worked if you first invoked this.calculate() and then tried to assign this.sum = n;. But even in this case this was very wrong, since you were leaking variable n to the global namespace (when you do not explicitly initialize variable with var, it leaks to global namespace - window). So to illustrate what I mean - this could work:
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();
nis 5 after callingcalculate, only you are getting an exception before. Have a look at your error console.nto be 5, what should returnn? How did you test it?