【问题标题】:scope in javascript objectjavascript对象中的范围
【发布时间】:2013-02-17 14:42:57
【问题描述】:

这是我的代码:

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 是未定义的吗?我认为 return n 应该有所帮助,但我错了。

【问题讨论】:

  • n is 5 在调用calculate 之后,只有你之前得到了异常。看看你的错误控制台。
  • 你想做什么?您预计 n 何时为 5,应该返回什么 n?你是怎么测试的?

标签: javascript function object scope


【解决方案1】:

不确定您要做什么,但试试这个:

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】:

    这里我试着解释一下。

    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; 
    
    }
    

    【讨论】:

      【解决方案3】:

      您的构造函数似乎有一个错误。在分配之前,您正在阅读 n

      也许这样会更清楚:

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

      然后完全摆脱 n 值。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多