DEV Community

Discussion on: JavaScript; what's the meaning of `this`?

Collapse
 
lordliquid profile image
Robert Cutright • Edited

Another useful thing to note here..
When trying to obtain 'this' within an arrow function, 'this' could be referred to by the variable name of the object:

// let lib = require('custom-library');
const obj = { // note: the 'obj' can be used to access the 'this' you were looking for.
    method: () => console.log(obj), // 'obj' represents itself as 'this'
    another: function() {
        console.log(obj); // even better to use 'obj' in a function method scope too, because 'this' would walk up the proto chain and give you the global.
    },
    getMethod: () => {
        return () => {
            console.log(obj);
        }
    }
}

// Let's try it
obj.method();   // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }
obj.another();  // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }

// Let's try the other problem and see if this solves it as well.
let anotherObj = obj;
anotherObj.method(); // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }
anotherObj.another(); // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }

let another = obj.another;
another(); // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }

let method = anotherObj.getMethod();
method(); // { method: [Function: method], another: [Function: another], getMethod: [Function: getMethod] }

// Another test case
const func = () => {
    console.log(func);
}

func(); // [Function: func]

With that being said.. would it be better to just forget about the use of this and just use the objects name as a replacement?

disclaimer: Though, I haven't found any note-able pitfalls to this approach yet. I'd encourage you all to do your own research before using this method.