[英]How to create a javascript library that can be used in multiple projects?
So I have a custom-made javascript library that I use in multiple projects. 因此,我有一个自定义的javascript库,可在多个项目中使用。 The problem is that if I make a change in one of the projects, then I have to into all the projects that use that library and replicate the changes.
问题是,如果我在其中一个项目中进行了更改,则必须进入使用该库的所有项目并复制更改。 I want to be able to make the changes in the original library and all the projects that use/reference it are automatically updated.
我希望能够在原始库中进行更改,并且所有使用/引用它的项目都将自动更新。 How do I go about doing this in Visual Studio (2013)?
如何在Visual Studio(2013)中执行此操作?
You need to define contract (Called interface
in JAVA) to avoid changing the name of functions . 您需要定义协定 (JAVA中的Called
interface
)以避免更改功能名称。
Briefly, Don't change name of functions, Change implementation's function . 简要地说, 不要更改函数名称,请更改实现的函数 。
var api={}; /*"api" is namespace*/
api.myFn=function(a,b){
return a+b;
}
is Better than : 优于:
var myFn=function(a,b){
return a+b;
}
Best practices are to wrap the code of the WHOLE library with anonymous functions. 最佳做法是使用匿名函数包装WHOLE库的代码。
(function(api){
api.myFn=function(a,b){ /*"myFn" is attached to nameSpace*/
return a+b;
};
window.myLibrary=api; /*Publish your library to be used outside of anonymous function */
})({}) /*{} is the value of api*/
Then in other files/other projects , you can use it like so : myLibrary.myFn(4,5)
然后, 在其他文件/其他项目中 ,您可以像这样使用它:
myLibrary.myFn(4,5)
(function(api){ api.myFn=function(a,b){ /*"myFn" is attached to nameSpace*/ return a+b; }; window.myLibrary=api; /*Publish your library to be used outside of anonymous function */ })({}) /*{} is the value of api*/ console.log( myLibrary.myFn(4,5) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.