如何创建可重用的JavaScript组件

时间:2013-10-16 15:37:48

标签: javascript

我正在尝试创建一个可在任何Web应用程序中重用的JavaScript组件(仅允许纯js)。并且一次可以在网页上存在多个实例。

客户端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'); }
}());

我如何实例化上面的组件?

2 个答案:

答案 0 :(得分:2)

这是它的要点:

function MyComponent() {
  //constructor
}

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

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

以下是你如何使用它

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

MyComponent.doSomething();

答案 1 :(得分: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 );