Javascript - 在对象中存储功能 - 不好的做法? [英] Javascript - Storing function in object - bad practice?

查看:138
本文介绍了Javascript - 在对象中存储功能 - 不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

1。

Foo = {
    bar: function() {
        alert("baz");
    }   
}

Foo.bar() ;

vs。

2。

function bar() {
    alert("baz");
}

bar();

确实,第二个例子可能会稍微减少代码,但是当你开始获得很多功能时,它会变得凌乱。
我找到方式,方式,更清洁,例如,使用 Game.update()而不是使用updateGame();或类似。越来越深入,像 Game.notify.admin(id)等等,它给你甚至更漂亮的代码。

Sure, it might be slightly less code for the second example, but when you start to get lots of functions - it will get messy. I find it way, way, cleaner to, for example, use Game.update() instead of using updateGame(); or similar. When getting deeper, like Game.notify.admin(id) and so on, it gives you even prettier code.

通过在对象中存储函数有什么缺点吗?

推荐答案

第一种方法是首选。这样,您将明确定义函数的范围,而不是污染全局作用域。使用第一种方法没有缺点。只有upides: - )

The first approach is preferred. This way you are explicitly defining the scope of your functions instead of polluting the global scope. There are no downsides of using the first approach. Only upsides :-)

结论:总是使用第一种方法定义函数。第二个就像上世纪90年代的JavaScript,让我们过去休息一下,并使用正确的范围。

Conclusion: always use the first approach to define functions. The second is like javascript in the 90s, let's leave it rest in peace back in the past and use proper scoping.

这篇关于Javascript - 在对象中存储功能 - 不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆