[英]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.