我想每次为我创建的新对象返回一个新的处理程序。该处理程序采用一个对象参数。
function abc () {
var handle = function(position) {
// some code goes here
};
var obj1 = new SomeOBJ ();
obj1.handler = handle;
return obj1;
}
当我创建一个对象时,它工作正常,但是当我创建另一个对象时,前一个处理程序不再工作,只有最新对象的处理程序工作。
对我来说,看起来最近只创建了一个句柄,并且每次都附加到最新的对象。
这可能是什么原因?
谢谢。
最佳答案
我无法弄清楚您到底想做什么以及正在做什么。如果您尝试在类的每个实例上使用单独的方法,您可以在初始化时或 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;
关于javascript - 先前对象的处理程序不起作用。只有最后一个有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17143861/