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');

2 Answers 2

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
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and acceptable. I prefer your answer while i can access both element and class object. Thanks
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.

1 Comment

thank for answer but for @31piy's i can access both element and class object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.