The this Keyword

this is something I've kinda glossed over. Let me fix that now.

Here's an object with a more traditional (i.e. not fat arrow) method:

var some_object = {  
    key: "value",
    another_key: "another value",
    the_answer: 42,
    some_method: function () {
        console.log(this)
    }
}

Run some_object.some_method() and you'll print the following:

{ key: 'value',
  another_key: 'another value',
  the_answer: 42,
  some_method: [Function] }

Unsurprisingly, the value of this in a method is its object. But things get a little confusing when you have another function inside a method.

var some_object = {  
    key: "value",
    another_key: "another value",
    the_answer: 42,
    some_method: function () {
        function inner_function() {
            console.log(this)
        }
        inner_function()
    }
}

some_object.some_method()  

This prints undefined. What gives?

Welcome to the wacky world of this in JavaScript. There are all kinds of rules for how it works, one way around this problem is the following:

var some_object = {  
    key: "value",
    another_key: "another value",
    the_answer: 42,
    some_method: function () {
        function inner_function() {
            console.log(this)
        }
        inner_function.bind(this)()
    }
}

some_object.some_method()  

Pretty clunky right? bind is a method of every JavaScript function (in JavaScript, all functions are also objects) that takes an object and returns a new version of itself for which the this value is that object.

ES2015 has a better way:

var some_object = {  
    key: "value",
    another_key: "another value",
    the_answer: 42,
    some_method: function () {
        var inner_function = () => console.log(this)
        inner_function()
    }
}

some_object.some_method()  

This code prints out the object, like you would expect.

One of the features of an arrow function is that its this value is the same as its containing function.

That's not really why I like them so much, I just really dig the syntax, the fact that one-liners can omit curly braces, and that the value of that one line is what's returned in a one-liner.

Looking for a software developer?