如何复制(新实例)闭包函数

How to make copies (new instances) of a closure function?

本文关键字:实例 闭包 函数 新实例 复制 何复制      更新时间:2023-09-26

我有一个对象/函数/闭包(我认为是这三个?),我需要将它的单独实例应用于页面上的多个元素。

var NS = NS || {};
NS.PLAJAX = function(){
   var pub = {};
   var self = this;

   pub.Init = function(FormRef){      
     // do stuff
   };   
   self.aPrivateFunction = function(){      
      // do stuff
   }
   return pub;
}();

// Apply a *copy* to each element with the given class
$(function(){
   $('.el-form-wrapper').each(function(index, Element){
      // Attempt #1
       NS.PLAJAX.Init(Element); // Doesn't make copies! 
      //OR, Attempt #2      
      var Newbie = new NS.PLAJAX(); // Throws a "not a constructor" error
      Newbie.Init(Element);
   });
});

如何在每个元素上获取此闭包/对象的新实例?

你得到的只是一个对象。 但是,要使用 new 关键字,您需要一个函数(构造函数)。

无需从构造函数返回任何内容。 new 关键字创建一个新对象,使用该新对象调用该函数作为 this ,然后返回它。 公共方法应该分配给thisself)的属性,私有方法应该是局部变量。 你最终会得到这样的结果:

var NS = NS || {};
NS.PLAJAX = function(){
   var self = this;

   self.Init = function(FormRef){      
     // do stuff
   };   
   var aPrivateFunction = function(){      
      // do stuff
   }
};

// Apply a *copy* to each element with the given class
$(function(){
   $('.el-form-wrapper').each(function(index, Element){   
      var Newbie = new NS.PLAJAX();
      Newbie.Init(Element);
   });
});

我已经尝试过了,它对我有用,希望这对你有用

var NS = NS || {};
NS.PLAJAX = function(){
   var pub = {};
   var self = this;

   pub.Init = function(FormRef){      
     alert(FormRef);
   };   
   self.aPrivateFunction = function(){      
      alert("private");
   }
   return pub;
};

访问对象 NS

   $(function(){
  $('.el-form-wrapper').each(function(index, Element){
       var a=NS.PLAJAX();
       console.log(typeof(a));
       a.Init("gg"); // Doesn't make copies! 
          //OR, Attempt #2      
          var Newbie = new NS.PLAJAX(); // Throws a "not a constructor" error
          Newbie.Init("ff");
});
      });

查看演示