简体   繁体   中英

How do I create a reusable JavaScript component

I'm trying to create a JavaScript component that is reusable in any web application (pure js only allowed). And more than one instance can exist at a time on a web page.

Client 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'); }
}());

How would I instantiate the component above?

Here's the gist of it:

function MyComponent() {
  //constructor
}

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

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

And heres how you'd use it

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

MyComponent.doSomething();

I think what you are looking for is the constructor pattern . See explanations and the Car example on this page .

Excerpt from the article:

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM