[英]Should I encapsulate my javascript library?
I have about 600 lines of javascript that performs ajax calls, dom manipulation, test processing, and other things. 我大约有600行javascript,它们执行ajax调用,dom操作,测试处理和其他操作。
I want to make it a library that others can use. 我想使其成为其他人可以使用的库。
What are the steps to doing this? 采取哪些步骤?
My first thought was to encapsulate the entire library in the module pattern. 我的第一个想法是将整个库封装在模块模式中。 Someone suggested this earlier to help with a www.jshint.com issue.
有人早些时候建议这样做,以帮助解决www.jshint.com问题。
But I thought it might be a good idea in general. 但我认为这通常是个好主意。
Should I encapsulate my entire library? 我应该封装我的整个库吗?
Information Hiding is an old and well known way to make code safer and more modularized. 信息隐藏是一种使代码更安全,更模块化的古老方法。 Its one of the basic principles behind many awesome things like Abstract Data Types and Object Oriented Programming
它是许多很棒的事物(例如抽象数据类型和面向对象编程)背后的基本原理之一
(And yes, local variables and the module pattern are the only way to hide code in Javascript) (是的,局部变量和模块模式是在Javascript中隐藏代码的唯一方法)
var MyModule = (function(){
//variables in the wrapper function are local and
// can't be seen elsewhere
var my_var;
function my_private_implementation_function(){ ... }
function my_api_function(){
}
//return public functions
return {
my_api_function: my_api_function
};
}()); //immediatelly run the module code
//and set MyModule to the return value
//Now we can use things exported from the module
MyModule.my_api_function();
//but we can't access the prvate stuff
MyModule.my_var; //can't do this
I think the way you'd encapsulate the code, how you would expose it to the DOM, interact with it or any of those things is fully dependent on the way you would want to use it and of the context in which you would use it. 我认为您封装代码的方式,如何将其公开给DOM,与之交互或进行其他任何事情完全取决于您要使用它的方式以及使用它的上下文。 。 Coding patterns all serve their own unique purpose so pick a pattern because of what it provides to you, for instance in coding ease or performance or variable exposure.
编码模式都有其独特的用途,因此请选择一种模式,因为它会为您提供什么,例如在编码简便性,性能或可变曝光率方面。 So if you'd ask me, don't use a pattern because you should use a pattern, but because it does what you want it to do best.
因此,如果您要问我,请不要使用模式,因为您应该使用模式,但是因为它可以做到您希望它做得最好。
Besides that i would advise encapsulation (if you're talking about wrapping your code in a closure) to not clutter the global object and thus avoid variable collisions which make your code more reliable since there's less risk of bugs. 除此之外,我建议封装(如果您正在谈论将代码包装在闭包中)不要使全局对象混乱,从而避免变量冲突,因为它们减少了错误的风险,从而使代码更可靠。
Hope it helps PM5544... 希望它对PM5544有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.