Javascript 前一个对象的处理程序不工作。只有最后一个有效

Javascript 前一个对象的处理程序不工作。只有最后一个有效,javascript,function,handler,Javascript,Function,Handler,我希望每次为我创建的新对象返回一个新的处理程序。此处理程序接受一个对象参数 function abc () { var handle = function(position) { // some code goes here }; var obj1 = new SomeOBJ (); obj1.handler = handle; return obj1; } 当我创建一个对象时,它工作正常,但是当我创建另一个对象时,前面的处理程序不再工作

我希望每次为我创建的新对象返回一个新的处理程序。此处理程序接受一个对象参数

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;

实际上,我正在从函数返回
obj1
,并保存到列表中。我已经编辑了我的代码。创建一些JSFIDLE示例怎么样?