问题
I try this:
function MovableLine (line, number) {
this.line = line;
this.number = number;
}
MovableLine.prototype.start = function (e) {
alert(this.number);
alert(this);
};
and then:
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);
result:
first alert: undefined
second alert: object SWGPathElement
How to get my object movableLine from start()?
回答1:
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);
};
}
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);
来源:https://stackoverflow.com/questions/26550876/method-of-object-as-handler