tags:

views:

36

answers:

2

I want to create a plugin called 'myPlugin'. Which method should I use and what is the difference between these two methods? Please tell me the advantages too. I am from designing background and not much programming knowledge.

 var myPlugin = {
     myId:"testId",        
     create:function(){},
     destroy:function(){}
}

OR

function myPlugin() {
this.myId = "testId";
this.create = function(){};
this.destroy = function(){};

}

A: 

I would go for something like:

function myPlugin () {
    this.myId = "testId";
    this.create = createFunction;
    this.destroy = destroyFunction;
}
function createFunction() {
    alert('createFunction() called');
}
function destryFunction() {
    alert('destroyFunction() called');
}

my plugin = new myPlugin();
kender
+2  A: 

The first method creates a singleton object, stored in a variable called myPlugin. Only one instance of the "plugin" exists in this form. If you know you will only need one instance, this approach is a good choice. You can also extend its capabilities to allow for both public and "private" properties by using the Module Pattern.

The second method defines an object constructor function, which will allow you to make multiple instances of the object using the new keyword. This will allow you to use as many copies of the object as you might need, and sets you up with the ability to add onto the object using its prototype.

Jimmy Cuadra