0

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?

1
  • Do you have a specific question? Is something in your code not working? What do you expect to be newing? Commented Oct 16, 2013 at 15:40

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I think function MyComponent() {...} would be more standard.
Completely! Don't know why I wrote it that way.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.