I want to create a plugin called 'myPlugin'. Which method should I use and what开发者_StackOverflow中文版 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(){};
}
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
.
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();
精彩评论