javascript - 先前对象的处理程序不起作用。只有最后一个有效

标签 javascript function handler

我想每次为我创建的新对象返回一个新的处理程序。该处理程序采用一个对象参数。

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/

相关文章:

javascript - 如何在滚动时使用 jQuery 显示/隐藏 div?

javascript - 如何使用带有 location.reload 方法的 Javascript 控制 F5

javascript - 响应式等高div不指定高度

PHP计算财政年度

javascript - 如何从 JavaScript 中的字符串中删除 div 和 span 以外的 HTML 标记?

python - 检查是否设置了唯一一个可选函数参数并获取其值

返回两个输出的函数

java - 屏幕关闭时计时器停止工作

Java - spring控制台应用程序全局异常处理程序

java - 如何在从 Unity 调用的 Java 插件中创建 Android 处理程序