在 JavaScript 中从另一个方法返回对方法的多次调用揭示模块模式
我正在为当前项目尝试揭示模块模式。
我在几个方法的顶部有 init 方法,在这些方法中我设置变量并调用模块在被适当的事件处理程序调用时正确运行所需的方法。
我有一个 init 方法,目前看起来像这样:
function init(elem) {
var width,
height,
tipHeight,
tipWidth,
topMargin,
leftMargin;
return appendTip();
};
所以这会返回对appendTip 方法的调用。
在另一个模块中,设置如下所示:
function init() {
var width = 0,
$siteNavListElem = $('.nav-SiteNav .nav-list > li'),
$subNav = $('.subNav > li > ul');
appendSubNav();
getWidth();
};
现在有两次对各个方法的调用。这段代码工作正常,但想知道它是否可以更简洁?
我如何返回这两个?归还他们是称呼他们的最佳方式吗?
谢谢。
I am experimenting with the revealing module pattern for a current project.
I have init methods at the top of several methods where i set up variables and call methods necessarry for the modules to function correctly when they are called by their appropriate event handlers.
I have a init method that looks like this currently:
function init(elem) {
var width,
height,
tipHeight,
tipWidth,
topMargin,
leftMargin;
return appendTip();
};
So this returns a call to the appendTip method.
In another module the set up looks like this:
function init() {
var width = 0,
$siteNavListElem = $('.nav-SiteNav .nav-list > li'),
$subNav = $('.subNav > li > ul');
appendSubNav();
getWidth();
};
So now there are two calls to individual methods. This code works fine but wondered if it could be any neater?
How do i return both of these? Is returning them the best way to call them?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,我不确定您是否完全遵循揭示模块模式。该模式解释了返回包含对象的公共接口的公共对象。因此,从函数内部返回函数并不真正构成该模式。对于该模式,您正在考虑做这样的事情
基本上,您从封装函数(revealingPattern)返回的所有内容都是一个匿名对象,其中包含命名属性,这些属性是允许您使用的revealingPattern对象的公共接口。
然而,我对这种模式的抱怨是,它没有告诉您返回对象中的属性是函数还是变量!
因此,如果您确实想实现该模式,您可能需要稍微重构一下代码。否则你几乎可以采取任何你想要的方法。它们都是有效的,但只是不是揭示模块模式。
Actually I am not sure if you are following the revealing module pattern at all. The pattern explains returning a public object that contains the public interface of your object. So returning a function from within a function doesn't really constitute that pattern. For that pattern you are looking at doing something like this
Basically all you are returning from the encapsulating function (revealingPattern) is an anonymous object that contains named properties which are the public interface of the revealingPattern object that you are allowed to use.
My gripe with this pattern however is that it doesn't tell you whether a property in the returned object is a function or a variable!
So you might want to refactor your code a bit if you really want to implement the pattern. Otherwise you can pretty much take any approach you would like. They are all valid but just not the revealing module pattern.