javascript对象中的范围

时间:2013-03-03 12:50:12

标签: javascript function object scope

这是我的代码:

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未定义?我认为应该回来帮助,但我错了。

3 个答案:

答案 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

要回答您的问题,nundefined,因为当您尝试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; 

}