[英]Handler for previous objects not working. Only last one works
I want to return a new handler every time for a new object that I create. 我想每次为我创建的新对象返回一个新的处理程序。 This handler takes one object argument.
该处理程序采用一个对象参数。
function abc () {
var handle = function(position) {
// some code goes here
};
var obj1 = new SomeOBJ ();
obj1.handler = handle;
return obj1;
}
When I create one object it works fine, but when I create another object the previous handler doesnot work anymore, only the latest object's handler works. 当我创建一个对象时,它工作正常,但是当我创建另一个对象时,先前的处理程序不再起作用,只有最新对象的处理程序可以工作。
For me it looks like the latest only one handle is being created and is attached to the latest object every time. 对我来说,似乎只有最新的一个句柄正在创建,并且每次都附加到最新的对象。
What can be the reason for this? 这可能是什么原因?
Thank you. 谢谢。
I can't figure out what you exactly are trying to do and what you are doing. 我无法弄清楚您到底想做什么和正在做什么。 If you are trying to have separate methods on each instance of a class you can assign the method on initialize or after the init function:
如果要在类的每个实例上尝试使用单独的方法,则可以在初始化时或在init函数之后分配该方法:
function Klass() {
// Assign a specific method for each instance of this class:
this.handler = function() {};
}
// This method is the same around all instances of this class:
Klass.prototype.otherMethod = function() {};
// Create three instance of the class to compare:
var klass = new Klass();
var klass2 = new Klass();
var klass3 = new Klass();
// See the handler method is different on each instance:
console.log(klass.handler === klass2.handler); // false;
// And the methods set through the prototype is shared:
console.log(klass.otherMethod === klass2.otherMethod); // true;
// Give klass3, klass2's handler:
klass3.handler = klass2.handler;
// These are shared as well because of what we just did.
console.log(klass2.handler === klass3.handler); // true;
klass3.otherMethod = function() {};
// Because klass3 have got another method assigned to 'otherMethod' this will return false
console.log(klass2.otherMethod === klass3.otherMethod); // false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.