2013-10-16 46 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); 
相关问题