2013-10-16 87 views
0

我想創建一個可在任何Web應用程序中重用的JavaScript組件(僅允許使用純js)。一次可以在網頁上存在多個實例。我如何創建一個可重用的JavaScript組件

客戶端HTML

<head runat="server"> 
    <title></title> 
    <link href="StyleSheet.css" rel="stylesheet" /> 
    <script src="MyComponent.js"></script> 
    <script type="text/javascript"> 
     window.onload = function() { 
      MyComponent.init(); 
     }; 
    </script> 
</head> 

MyComponent.js

var MyComponent = {}; 

(function() { 
    var ns = MyComponent; 
    ns.init = function() { alert('test'); } 
}()); 

我將如何實例化上面的成分?

+0

你有一個具體的問題?你的代碼中的某些東西無法工作?你期望什麼是'新'? –

回答

2

下面是它的要點:

function MyComponent() { 
    //constructor 
} 

MyComponent.prototype.doStuff = function() { 
    //method 
} 

MyComponent.doSomething = function() { 
    //static method 
} 

而且繼承人你如何使用它

var component = new MyComponent(); 
component.doStuff(); 

MyComponent.doSomething(); 
+1

我覺得'function MyComponent(){...}'會更標準。 – Christophe

+0

完全!不知道我爲什麼這樣寫。 –

1

我想你正在尋找的是構造模式。請參閱解釋和汽車示例on this page。從文章

摘錄:

function Car(model, year, miles) { 
    this.model = model; 
    this.year = year; 
    this.miles = miles; 
    this.toString = function() { 
    return this.model + " has done " + this.miles + " miles"; 
    }; 
} 
// Usage: 
// We can create new instances of the car 
var civic = new Car("Honda Civic", 2009, 20000); 
var mondeo = new Car("Ford Mondeo", 2010, 5000); 
相關問題