0

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');
dtlvd
  • 457
  • 1
  • 8
  • 21
Khean
  • 99
  • 1
  • 13

2 Answers2

3

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
    });
}
31piy
  • 23,323
  • 6
  • 47
  • 67
  • Simple and acceptable. I prefer your answer while i can access both element and class object. Thanks – Khean Apr 10 '18 at 10:26
1

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114