![](/img/trans.png)
[英]Should I put the version number of my JavaScript library in the file name?
[英]How should I name my javascript library functions so they are differentiable from plain old javascript?
我正在js中編寫自定義UI構建器。 它使用工廠的實現來構建元素。 為了確保哪些函數是庫的一部分而哪些是普通的舊javascript的一部分,我使用了function _FunctionName()
的命名約定。 但是,我發現總是做Factory._FunctionName()
很乏味。
我應該刪除命名約定( function FunctionName()
)還是堅持它?
是否有關於制作這樣的庫的命名約定常見/最佳實踐?
編輯:
var __PanelFactory = function () {
//"private"
var Panels = [];
//exposed
function _GetPanel(id) {
//etc
}
return {
_GetPanel: _GetPanel,
};
};
var Factory = new __PanelFactory();
Factory. //this will show certain plain javascript functions
//like toString, constructor, hasOwnProperty, isPrototypeOf, etc...
//note that even jQuery can have the previous list used with something like
$(selector).
//So to differentiate I made sure my functions start with _
Factory._GetPanel(1);
//Should I just make it easy on myself and allow
Factory.GetPanel(1);
//Or is there value in leaving the naming convention in?
以下是javascript中一些非常常見的約定。
通常在ALL_CAPS_WITH_UNDERSCORES中
var MAX_COUNT = 100;
var BASE_URL = "http://example.com/api/";
通常在lowerCamelCase中
var currentCount = 0;
var userName = "timrwood";
通常在UpperCamelCase中
function Factory(){}
var factory = new Factory();
通常在lowerCamelCase中
Factory.prototype.getPanel = function(){};
var factory = new Factory();
var panel = factory.getPanel();
通常在_lowerCamelCaseWithAUnderscorePrefix中;
Factory.prototype._fetchPanel = function(){};
Factory.prototype.getPanel = function() {
return this._fetchPanel();
}
SO上已經有一個問題鏈接到關於Javscript編碼約定(包括命名)的好文檔:
你問過的關鍵部分:
這在某種程度上是可選的,因為PanelFactory
不會與普通的Javascript沖突。 如果您要使第三方使用公共API,它可能會與其他庫發生沖突,但是:
var MyApp = MyApp || {};
MyApp.__PanelFactory = function () { // ...
_
)。 您不需要下划線,因為已經使用JavaScript一段時間的人知道每個對象( toString
等)中內置的默認實例范圍函數:
MyApp.PanelFactory = function () {
// ...
function GetPanel(id) {
//etc
}
這只是一個標准慣例。 它無法區分內置函數,但正如我在上一個項目中所說,您不需要。
MyApp.PanelFactory = function () {
// ...
function getPanel(id) {
//etc
}
這將幫助您區分命名空間,對象構造函數和對象的實例(您希望存在自定義實例范圍的函數,通常稱為“方法”)。
var factory = new MyApp.PanelFactory();
var panel = factory.getPanel();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.