gpt4 book ai didi

javascript - 模块模式中的私有(private)方法 : TypeError: undefined is not a function

转载 作者:行者123 更新时间:2023-11-30 12:32:00 25 4
gpt4 key购买 nike

我正在尝试在 javascript 中实现经典的模块模式,已讨论 herehere .但是我的私有(private)方法不起作用。我有以下测试代码。

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.sayStuffPrivate( stuff );

这里,this 指的是您实际从 sayStuff 函数返回的对象。它没有名为 sayStuffPrivate 的属性。因此,this.sayStuffPrivate 将被评估为 undefined,并且由于您将其用作函数,因此它会因该错误而失败。

你应该利用闭包属性并像这样调用它

sayStuffPrivate( stuff );

关于javascript - 模块模式中的私有(private)方法 : TypeError: undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27416356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com