Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" on Javascript object methods [duplicate]

Tags:

javascript

I am confused about javascript object methods on This and the implementation of ()=> instead of function(){},

Would you care to explain the behaviour of this: thanks

const obj = {

    prop : 123,

    test : function (){
        console.log(this.prop);
    },

    test2 : ()=>{
        console.log(this.prop);
    },
}

console.log(test()); //results to 123
console.log(test2()); //results to undefined
like image 763
grit Avatar asked Sep 02 '25 07:09

grit


2 Answers

'this' keyword refers to the object context, when you call obj.test() that logs the property of that object (obj.prop). With the new method syntax introduced in ES6 we can omit the colon and the function keyword.

const obj = {
    prop : 123,
    test(){
        console.log(this.prop);
    },
    test2: () => {
        console.log(this.prop);
    }
}

obj.test();   //123
obj.test2();  //undefined

If we use the 'this' keyword in a method then the value of 'this' is the calling object. Arrow functions inherently bind, an already defined 'this' value to the function itself that is NOT the calling object. In the code snippet above, the value of 'this' is the global object, or an object that exists in the global scope, which doesn’t have a 'prop' property and therefore returns undefined.

like image 73
sonEtLumiere Avatar answered Sep 04 '25 21:09

sonEtLumiere


According to You Don't Know JS: ES6 & Beyond. Chapter 2. Syntax arrow functions are not only for shorter syntax for function declaration. It's about changing THIS behaviour.

In arrow function THIS is not dynamic, it's lexical.It points to surrounding scope, which is global so this.prop is undefined.

Example of correct using arrow function:

var controller = {
    makeRequest: function(..){
        btn.addEventListener( "click", () => {
            // ..
            this.makeRequest(..);
        }, false );
    }
};

We used arrow function for callback. So we can pass THIS from surrounding scope.

If we try to use regular function we have to pass THIS using var:

var controller = {
    makeRequest: function(..){
        var self = this;

        btn.addEventListener( "click", function(){
            // ..
            self.makeRequest(..);
        }, false );
    }
};
like image 23
Dmitry Vdovichenko Avatar answered Sep 04 '25 20:09

Dmitry Vdovichenko