2013-02-27 140 views
0

我想將此代碼轉換爲命名空間以使其更清潔並避免污染全局命名空間。我是相當新的這一點,可以使用一些指導或例子我會怎麼下面的代碼轉換成JavaScript命名空間...使用javascript命名空間

 function Validator(fields) { 
    this.fields = fields; 
} 

Validator.prototype.validate = function(form) { 
    for(var i = 0, l=this.fields.length; i < l; i++) { 
    alert(this.fields[i].value); 
     if (this.fields[i].value == 0) { 
      alert("The field is empty"); 
      return false; 
     } 
    } 
} 

var validator = new Validator([ "username", "password"]); 

function runValidate(form) { 
validator.validate(form); 
    } 

(我知道這OO的方法來驗證OTT!)我從像這樣的「runValidate(this.form)」形式的按鈕中調用此runValidate。感謝您的任何幫助或建議。

+0

難道'runValidate'函數真的需要嗎?它只能節省7個字符。 – Bergi 2013-02-27 10:14:25

+0

謝謝。我該怎麼做而不是呢? – 2013-02-27 13:29:18

+0

只需從按鈕 – Bergi 2013-02-27 13:43:44

回答

2

命名空間只是JavaScript對象,例如

var myNamespace = {}; 
myNamespace.Validator = function(fields) { 
    ... 
} 
myNamespace.Validator.prototype.validate = function(form) { 
    ... 
} 
+0

感謝您的回答。我應該使用我的runValidate函數嗎?我將如何設置var驗證器? – 2013-02-27 13:28:57

+0

will var validator = new Validator([「username」,「password」]);變成var validator = new myNamespace.Validator([「username」,「password」]); ? – 2013-02-27 13:54:28

+0

正確,您現在調用'new myNamespace.Validator'而不是'new Validator'。然後使用validator.validate,就像@Bergi所建議的那樣,我認爲沒有'runValidate'函數的意義。 – 2013-02-27 14:28:38

1

JavaScript沒有本地命名空間,但你可以使用簡單明瞭的對象來模擬。這裏有一個簡單的實現一個命名空間效用函數:

function namespace(namespaceString) { 
    var nodes = namespaceString.split('.'), 
     parent = window, 
     currentNode;  

    for(var i = 0, length = nodes.length; i < length; i++) { 
    currentNode = nodes[i]; 
    parent[currentNode] = parent[currentNode] || {}; 
    parent = parent[currentNode]; 
    } 

    return parent; 
} 

你可以使用這樣的:

var MyApp = namespace("MyApp"); 
MyApp.Validator = function(fields) { 
    this.fields = fields; 
} 

var validator = new MyApp.Validator(["username", "password"]); 
// this also works: 
var validator = new namespace("MyApp.Validator")(["username", "password"]); 

這將讓你poluting全局命名空間,但你仍然有一些全局變量: MyApp在這種情況下和您的命名空間中的任何其他根節點。

+0

非常感謝。表單中按鈕的函數調用是否保持不變? – 2013-02-27 12:14:54

+0

是的。即使這不是最好的方式,它應該可以正常工作。 – cezar 2013-02-27 13:29:15