对象作为处理程序的方法 [英] Method of object as handler

查看:77
本文介绍了对象作为处理程序的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试:

function MovableLine (line, number) {
    this.line = line;
    this.number = number;
}

MovableLine.prototype.start = function (e) {

    alert(this.number);
    alert(this);
};

然后:

var mline = this.xAxis[0].plotLinesAndBands[plotLinesCount].svgElem;
                mline.css({
                    'cursor': 'pointer'
                });
                mline.translate(0, 0);
                movableLine = new MovableLine(mline, 10);
                movableLine.line.on('mousedown', movableLines[plotLinesCount].start);

结果:
第一警报:未定义
第二次警报:对象SWGPathElement

如何从start()获取我的对象movableLine?

result:
first alert: undefined
second alert: object SWGPathElement

How to get my object movableLine from start()?

推荐答案

我建议不要将原型用于事件方法.将函数分配为对象属性,然后缓存this引用:

I would recommand to not use prototype for event methods. Assign the function as an object property and also, cache the this reference :

function MovableLine (line, number) {
    var self = this; //Caching
    this.line = line;
    this.number = number;
    this.start = function (e) {

        alert(self.number);
        alert(self);
    };
}

或者,如果您绝对想使用.prototype,则可以使用点击捕捉器:

Alternatively, you can use a click catcher if you absolutely want to use .prototype:

function MovableLine (line, number) {
    var self = this; //Caching
    this.line = line;
    this.number = number;
    this.clickCatcher = function () {
        self.start.apply(self, Array.prototype.slice.call(arguments, 0));
    };
}

MovableLine.prototype.start = function (e) {

    alert(this.number);
    alert(this);
};

//And you event binding:
movableLine.line.on('mousedown', movableLines[plotLinesCount].clickCatcher);

这篇关于对象作为处理程序的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆