我试图在javascript中实现一个经典模块模式,讨论here和here。但我的私人方法不起作用。我有以下的测试代码。模块模式中的私有方法:TypeError:undefined不是函数
var jsStuff = (function() {
// Private
var sayStuffPrivate = function (stuff) {
console.log("I am a private method: " + stuff);
return true;
};
// Public
return {
sayStuff: function (stuff) {
console.log("I am a public method: " + stuff);
this.sayStuffPrivate(stuff);
return true;
}
}
}());
当我尝试运行此,我得到如下:
> jsStuff.sayStuff('blah');
test.js:16 I am a public method: blah
test.js:17 Uncaught TypeError: undefined is not a function
缺少什么我在这里?
这不是一种方法,因为这意味着它不再是私人的。这只是一个本地功能,应该这样访问;而不是通过'this.'像你的对象的公共属性。 – Bergi 2014-12-11 06:06:54
请注意,函数内* this *的值完全取决于您如何调用函数(或通过使用* bind *),而非词汇(或函数的创建方式)。 – RobG 2014-12-11 06:17:08