gpt4 book ai didi

javascript - 用构造函数揭示模块模式

转载 作者:可可西里 更新时间:2023-11-01 01:18:53 24 4
gpt4 key购买 nike

我在找出实现它的最佳方法时遇到了一些麻烦。

我想要一个具有构造函数的模块,该构造函数接受一个参数,该参数存储它以供以后在模块中使用。

var ModuleB = function(moduleA) {
this.moduleA = moduleA;
}

ModuleB.prototype = function() {
//private stuff/functions
function someMethod() {
moduleA.doSomething();
}

//public api
return {
someMethod : someMethod
};
}();

在其他文件中

//ModuleA defined elsewhere
var moduleA = new ModuleA();

//...

var module = new ModuleB(moduleA);
module.someMethod();

现在上面的someMethod中,moduleA是未定义的,而this是全局窗口对象。有人可以解释一下我将如何访问 moduleA 吗?我不明白 this.moduleA = moduleA; 在构造函数之后发生了什么。我不是真正的 JavaScript 开发人员,所以如果我在这里使用了错误的模式或其他什么,请随时提出意见。

最佳答案

您非常接近,但是您在 someMethod 的定义中遗漏了一些重要的东西。

编辑:如果您在 ModuleB 中更改模块属性的名称,则更容易判断哪些有效,哪些无效:

var ModuleA = function() {}

ModuleA.prototype = (function () {
return {
someMethod: function () {
return 'foo';
}
};
}());

var ModuleB = function(moduleA) {
this.innerModule = moduleA;
}

ModuleB.prototype = (function () {
return {
doStuff: function () {
return this.innerModule.someMethod();
}
};
}());

var moduleA = new ModuleA();

var moduleB = new ModuleB(moduleA);
console.log(moduleB.doStuff()); // prints "foo"

http://jsfiddle.net/mN8ae/1/

关于javascript - 用构造函数揭示模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380833/

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