我正在尝试在javascript中实现经典模块模式,讨论here和here。但我的私人方法不起作用。我有以下一些测试代码。
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
我在这里缺少什么?
答案 0 :(得分:3)
this.sayStuffPrivate( stuff );
此处,this
指的是您实际从sayStuff
函数返回的对象。它没有名为sayStuffPrivate
的属性。因此,this.sayStuffPrivate
将被评估为undefined
,因为您将其用作函数,所以它会因错误而失败。
你应该利用closure属性并像这样调用它
sayStuffPrivate( stuff );
答案 1 :(得分:0)
如果没有这个,你应该调用sayStuffPrivate。试试这个:
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 );
sayStuffPrivate( stuff );
return true;
}
}
}());