2

Here's my code:

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

        this.calculate();
    }

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

var mytest = new Test();

Could you please explain why n is undefined? I thought return n shoud help but I was wrong.

2
  • n is 5 after calling calculate, only you are getting an exception before. Have a look at your error console. Commented Mar 3, 2013 at 12:53
  • What are you trying to do? When do you expect n to be 5, what should return n? How did you test it? Commented Mar 3, 2013 at 12:55

3 Answers 3

2

Your constructor function seems to have a bug. You are reading from n before assigning it.

Perhaps this would be clearer:

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

Then get rid of the n value altogether.

Test.prototype.calculate = function() { return 5; }
Sign up to request clarification or add additional context in comments.

Comments

0

Here I try to explain a bit.

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
}

correct behavior( what you wanted)

function Test() {

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

}

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.