Reputation: 99
I'm new to JavaScript class. I have one JavaScript class. What I want is in console.log
will output result of class object not this element (element that mousedown). How can I write that?
function Transformer (output) {
this.output = output;
$(output+' .object').mousedown(function(e){
console.log(this);
});
}
var test = new Transformer('.console');
Upvotes: 0
Views: 70
Reputation: 40653
This has been asked a lot (like e.g. JavaScript Callback Scope) but I thought I should mention that this can also be resolved using arrow functions in ECMAScript 6 like below:
function Transformer (output) {
this.output = output;
$(output+' .object').mousedown((e) => {
console.log(this);
});
}
var test = new Transformer('.console');
However using arrow functions means you are losing the event target context (which you can probably recover using e.currentTarget
I am mentioning this because chances are all the sources are older than ES 6 and might not mention this.
Check ES6 compatibility for platforms that currently support arrow functions.
Upvotes: 1
Reputation: 23859
If you want to print the class object itself, you need to save a reference to the context in another variable, because this
in the anonymous function points to the context of the anonymous function itself:
function Transformer (output) {
var self = this;
this.output = output;
$(output+' .object').mousedown(function(e){
console.log(self); // will print the object itself
});
}
Alternatively, you can use arrow function to skip saving a reference altogether:
function Transformer (output) {
this.output = output;
$(output+' .object').mousedown(e => {
console.log(this); // will print the object itself
});
}
Upvotes: 3