Creating a Javascript plugin
I want to create a plugin called myPlugin. Which method should you use and what is the difference between the two methods? Please tell me about the benefits too. I am from background design and do not have much programming knowledge.
var myPlugin = {
myId:"testId",
create:function(){},
destroy:function(){}
}
OR
function myPlugin() {
this.myId = "testId";
this.create = function(){};
this.destroy = function(){};
}
a source to share
The first method creates a singleton object stored in a variable named myPlugin
. There is only one instance of the "plugin" on this form. If you know you only need one instance, this approach is a good choice. You can also extend your capabilities to provide both public and "private" properties using the Module Pattern .
The second method defines an object constructor function that will allow you to make multiple instances of an object using a keyword new
. This allows you to use as many copies of the object as you need, and gives you the ability to add to the object using prototype
.
a source to share
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();
a source to share