执行 javascript“方法”;从对象调用其他方法时默认情况下
我读到,在 javascript 中不要使用太多全局变量是一个很好的做法,因此我尝试将一些与我的应用程序的导航按钮相关的功能打包在一个变量中,如下所示:
var navs = {
projects: function(){
main.removeClass().addClass('showing_projects');
//... other code
},
line_items: function(){
main.removeClass().addClass('showing_line_items');
//... other code
},
media: function(){
main.removeClass().addClass('showing_media');
//... other code
}
}
这样我就可以
navs.projects()
显示项目。我的问题是,我有一个 showNotify() 函数,我需要在调用任何 navs.projects()、navs.line_items() 或 navs.media() 后运行它。我觉得将这个 showNotify() 行添加到这三个属性/方法中并不干燥。有没有一种方法可以让 showNotify() 在每次调用这三个方法时运行?
谢谢
I have read that it is a good practice to not use too many global variables in javascript, so I am trying to package some functions related to navigation buttons of my app in a single variable like this:
var navs = {
projects: function(){
main.removeClass().addClass('showing_projects');
//... other code
},
line_items: function(){
main.removeClass().addClass('showing_line_items');
//... other code
},
media: function(){
main.removeClass().addClass('showing_media');
//... other code
}
}
So that I can do
navs.projects()
to show the projects. My question is, I have this function showNotify() that I need to run after calling any of the navs.projects(), navs.line_items(), or navs.media(). I feel that it is not DRY to have this showNotify() line added to each of these three properties/methods. Is there a way that I can have showNotify() run each time these I call these three methods?
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以参数化每个函数的不同部分:
并像这样使用:
您还可以创建一个函数生成器,如下所示:
然后像这样创建函数:
但我不认为调用
showNotify< /code> 在每个函数中都是一件大事。
You could parameterize the parts of each of those functions that are different:
And used like this:
You might also create a function generator, like this:
And then create your functions like this:
But I don't think calling
showNotify
in each function is a big deal.将
showNotify()
添加到每个方法的末尾并不违反 DRY。违反 DRY 的行为是复制/粘贴showNotify()
的内容而不是调用它。据我所知,没有比添加调用来实现目标更简洁的方法了。即使有,这样做也是一个非常糟糕的主意,因为调用这些函数会产生一些阅读代码的人根本看不到的效果。
It isn't a violation of DRY to add
showNotify()
to the end of each of these methods. A violation of DRY would be copy/pasting the contents ofshowNotify()
instead of calling it.As far as I know, there is no way more succinct than adding the calls to achieve your goal. Even if there were, it would be a very bad idea to do so because calling the functions would have some effects not visible at all to the person reading the code for them.