Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.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_Jquery - Fatal编程技术网

Javascript 如何制作闭包函数的副本(新实例)?

Javascript 如何制作闭包函数的副本(新实例)?,javascript,jquery,Javascript,Jquery,我有一个对象/函数/闭包(我想这三个都是?),我需要将它的单独实例应用于页面上的多个元素 var NS = NS || {}; NS.PLAJAX = function(){ var pub = {}; var self = this; pub.Init = function(FormRef){ // do stuff }; self.aPrivateFunction = function(){ // do

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

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
调用函数,然后返回它。公共方法应该分配给
this
self
)的属性,私有方法应该是局部变量。你最终会得到这样的结果:

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");
});
      });

请参见

,但如果这样做,
PLAJAX
就不再是闭包了。@Nick:仍然会创建一个闭包,将函数
aPrivateFunction
封装在PLAJAX的每个实例中。你为什么认为这不是结束?你认为闭包是什么?我想我把闭包和自执行函数混淆了,比如
functiondosomething(){}()@Nick PLAJAX是一个构造函数。请注意,它每次在
每个
语句中运行时都会创建一个新的闭包