javascript插件制作学习-制作步骤

原生JavaScript插件开发学习

插件一般把它放到一个闭包用来与外部变量隔绝以防污染全局变量。

!(function(){
          
 })()

插件制作步骤:

(一)构造函数 使用时new一下生成新的实例

var myUtil=function(name,age){
    this.name=name;
    this.age=age;
}

(二)使用原型模式  可以让多个实例的使用一个方法

var myUtil=function(name,age){
    this.name=name;
    this.age=age;
}

myUtil.prototype={

  // 将构造函数置为MathUtil,这里一定要将constructor重新设置回MathUtil,不然会指向Object的构造函数 
  constructor:myUtil,
    add: function(a, b) {      
        var result= a + b;      
        alert("result == " + result);      
    }
}

(三)创建一个闭包用来与外部变量隔绝以防污染全局变量。把以上代码放入其中

(function(window){
   var myUtil=function(name,age){
         this.name=name;
         this.age=age;
    }

   myUtil.prototype={
        // 将构造函数置为MathUtil,这里一定要将constructor重新设置回MathUtil,不    然会指向Object的构造函数 
        constructor: MathUtil,
        add: function(a, b) {      
        var result= a + b;      
        alert("result == " + result);      
        }
  }
window.myUtil=myUtil;//把代码挂载到window上以便外面调用 })(window)

(四)使用时new一下就可以调用里面的方法了

!(function(window) {
         var myUtil = function(name, age) {
                    this.name = name;
                    this.age = age;
                }

          myUtil.prototype = {
                    //将构造函数置为myUtil,这里一定要将constructor重新设置回myUtil,不 然会指向Object的构造函数 
                    //有轻度强迫症的表示最好重定向回来,避免挖坑
             constructor: myUtil,
                    add: function(a, b) {
                        var result = a + b;
                        alert("result == " + result);
                    }
                }
           window.myUtil = myUtil; //把代码挂载到window上以便外面调用
})(window)

            var v1 = new myUtil("hellow", 14);
            v1.add(3,5);

这样一个JavaScript插件小demo就完成了

猜你喜欢

转载自www.cnblogs.com/zimengxiyu/p/9781324.html