Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript插件创建_Javascript_Oop - Fatal编程技术网

Javascript插件创建

Javascript插件创建,javascript,oop,Javascript,Oop,我想创建一个名为“myPlugin”的插件。我应该使用哪种方法?这两种方法的区别是什么?请告诉我它的优点。我来自设计背景,没有太多编程知识 var myPlugin = { myId:"testId", create:function(){}, destroy:function(){} } 或 }我喜欢这样的东西: function myPlugin () { this.myId = "testId"; this.create =

我想创建一个名为“myPlugin”的插件。我应该使用哪种方法?这两种方法的区别是什么?请告诉我它的优点。我来自设计背景,没有太多编程知识

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


}

我喜欢这样的东西:

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

第一个方法创建一个单例对象,存储在名为
myPlugin
的变量中。此表单中只存在一个“插件”实例。如果您知道只需要一个实例,那么这种方法是一个不错的选择。您还可以通过使用扩展其功能,以允许公共和“私有”属性

第二种方法定义了一个对象构造函数,它允许您使用
new
关键字创建对象的多个实例。这将允许您根据需要使用尽可能多的对象副本,并使您能够使用其
原型添加到对象上

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