我有这段代码。
function coolStuff( name , options ) {
this.name = name;
this.options = options;
this.children = $(name).children();
this.children.each( function( index, value ) {
//How can I call this.processMoreCoolStuff if im using multiple instance?
this.processMoreCoolStuff( {} );
});
this.processMoreCoolStuff = function( param ) {
//Some processing of this.options here!
}
}
var coolStuffObj01 = new coolStuff( "#cs01", {} );
var coolStuffObj02 = new coolStuff( "#cs02", {} );
如果我使用多个实例,我怎么能调用this.processMoreCoolStuff()?对此最好的方法是什么?
答案 0 :(得分:1)
在each
回调函数中,this
指的是jQuery元素而不是coolStuff
函数。如果要在回调中访问它,您必须保留对coolStuff
实例的引用。
以下是一个例子:
function coolStuff( name , options ) {
this.name = name;
this.options = options;
this.children = $(name).children();
var self = this;
this.processMoreCoolStuff = function( param ) {
//Some processing of this.options here!
console.log("@processMoreCoolStuff", param);
}
this.children.each( function( index, value ) {
//How can I call this.processMoreCoolStuff if im using multiple instance?
self.processMoreCoolStuff( {name:name, txt:$(value).text()} );
});
}
var coolStuffObj01 = new coolStuff( "#cs01", {} );
var coolStuffObj02 = new coolStuff( "#cs02", {} );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cs01">
<div>Child 1</div>
<div>Child 2</div>
</div>
<div id="cs02">
<div>Child 1</div>
<div>Child 2</div>
</div>
&#13;
答案 1 :(得分:0)
只需coolStuffObj01.processMoreCoolStuff()
。
答案 2 :(得分:0)
如果要从每个实例(对象)访问该函数,请在函数last中使用此return this
。然后它将返回一个对象。
将该功能改写为
function coolStuff( name , options ) {
this.name = name;
this.options = options;
this.children = $(name).children();
this.children.each( function( index, value ) {
//How can I call this.processMoreCoolStuff if im using multiple instance?
this.processMoreCoolStuff( {} );
});
this.processMoreCoolStuff = function( param ) {
//Some processing of this.options here!
}
return this; // this line is added
}
现在,如果要访问它,请执行以下操作
var coolStuffObj01 = new coolStuff( "#cs01", {} );
coolStuffObj01.processMoreCoolStuff();
答案 3 :(得分:0)
您可以重构代码并使用构造函数&amp; prototype.Using prototype只创建实例&amp;将被共享。在构造函数中创建的函数被创建为使用构造函数创建的每个新对象的新对象。
function CoolStuff(name, options) {
this.name = name;
this.options = options;
this.children = $(name).children();
}
CoolStuff.prototype.processMoreCoolStuff = function(param) {
// rest of the code
}
CoolStuff.prototype.loopChild = function() {
this.children.each(function(index, value) {
this.processMoreCoolStuff();
});
}
var coolStuffObj01 = new coolStuff("#cs01", {});
var coolStuffObj02 = new coolStuff("#cs02", {});
答案 4 :(得分:0)
您必须使用.bind()
,只需更改分配顺序:
function coolStuff(name, options) {
this.name = name;
this.options = options;
this.children = $(name).children();
this.processMoreCoolStuff = function(param) {}; // <----move it up here
this.children.each(function(index, value) {
this.processMoreCoolStuff({}); // 2. it knows where to find the method
}.bind(this)); // <----1. when you bind "this"
}