[英]How to make copies (new instances) of a closure function?
I have an object/function/closure (I think it's all three?) and I need to apply separate instances of it to multiple elements on the page. 我有一个对象/函数/闭包(我认为这三个都是?)我需要将它的单独实例应用于页面上的多个元素。
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);
});
});
How can I get a new instance of this closure/object on each element? 如何在每个元素上获得此闭包/对象的新实例?
What you've got is just an object. 你得到的只是一个对象。 However, to use the
new
keyword, you want a function (a constructor). 但是,要使用
new
关键字,您需要一个函数(构造函数)。
There is no need to return anything from a constructor. 无需从构造函数返回任何内容。 The
new
keyword creates a new object, calls the function with that new object as this
, and then returns it. 在
new
关键词创建一个新对象,调用与新对象作为函数this
,然后返回。 Public methods should be assigned to properties of this
( self
) and private methods should be local variables. 公共方法应该分配给
this
( self
)的属性,private方法应该是局部变量。 What you'll end up with is something like this: 你最终得到的是这样的:
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);
});
});
i have tried this and it works for me hope this will work for u 我试过这个,它对我有用,希望这对你有用
var NS = NS || {};
NS.PLAJAX = function(){
var pub = {};
var self = this;
pub.Init = function(FormRef){
alert(FormRef);
};
self.aPrivateFunction = function(){
alert("private");
}
return pub;
};
// access the object NS //访问对象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");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.