您使用哪些 Javascript 编程模式?
我正在重新检查我的很多代码,并且不断回到这个问题:“我的所有 JS 类应该基于哪种模式?”
一些示例模式: http://www.klauskomenda.com/code/javascript-programming-patterns/
我最终采用了一种混合方法,具有基本的发布/订阅功能。我不使用原型或模块模式,我在构造函数中定义公共/私有属性/方法。
例如:
function ClassName(){
var _privateVar = 'private';
this.publicVar = 'public';
function _privateMethod(){};
this.publicMethod = function(){};
}
您在 JS 中经常使用哪些模式?出于什么目的?正规网站?完整的网络应用程序?是什么让你选择一种模式而不是另一种?
或者你认为这没有我想象的那么重要?
提前致谢。
编辑:好吧,我确实使用原型,只是不定义我的所有方法。但由于性能原因我倾向于这种方法?想法?
I'm in the process of re-examining a lot of my code, and I keep coming back to the question, "Which pattern should I base all of my JS classes on?"
Some example patterns:
http://www.klauskomenda.com/code/javascript-programming-patterns/
I ended up with a mix-in approach, with basic pub/sub functionality. I don't use prototype, or the module pattern, I define public/private properties/methods within the constructor.
For example:
function ClassName(){
var _privateVar = 'private';
this.publicVar = 'public';
function _privateMethod(){};
this.publicMethod = function(){};
}
What patterns do you often use in JS? For what purpose? Regular websites? Full web app? What made you pick one pattern over another?
Or do you think it matters less than I think it does?
Thanks in advance.
EDIT: well, I do use prototype, just not to define all my methods. But I'm leaning towards that approach due to performance? Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要考虑的一些事项
使用内部函数定义公共函数的成本更高,因为您为对象的每个实例化生成一个新函数。在原型上定义它使用方法的单个副本。
为了清楚起见,我总是像您一样对私有方法/属性使用下划线。
我还使用模块模式在类中定义静态私有方法。由于它们不需要访问实例,因此仅创建一次。
Some things to consider
Defining public functions with inner functions is more expensive since you generate a new function for every instantiation of an object. Defining it on the prototype uses a single copy of the methods.
I always use underscores for private methods/properties, as you have, for clarity.
I also use the module pattern to define static private methods within a class. Since they don't need access to the instance, they are only created once.
我们在tinyHippos 使用模块模式。
这是我们在此处
基本上你最终会得到:
We use the module pattern at tinyHippos.
Here is a blog post we wrote on the topic here
Basically you end up with: