繁体   English   中英

为什么在javascript中此模块模式上未定义?

[英]Why am I getting undefined on this module pattern in javascript?

为什么我在x.test()上变得未定义? 这是一个匿名函数。

var Calculator = function () {    
  // private stuff
  var x = 55;      
  return {
    // public members    
    y: x,
    test: function () {
      console.log(x);
    }
  };
}; 

var x = new Calculator(); 

console.log(x.y);
console.log(x.test());

您正在记录x.test返回值 ,该返回值是隐式undefined

console.log(x.y); // Logs 55
var x = x.test(); // Logs 55 (because of the console.log call in x.test)
console.log(x); // Logs undefined (because that's what x.test returned)

您是要从test方法中返回“ private” x吗?

// ...
return {
    y: x,
    test: function () {
        return x;
    }
}

因为您正在打印( console.log ),所以该函数的返回不返回任何内容。

只需在test函数中返回x值:

var Calculator = function () {
    // private stuff
    var x = 55;

    return {
        // public members
        y: x,
        test: function () {
            return x;
        }
    };
}; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM