Skip to content

Instantly share code, notes, and snippets.

@nikkaroraa
Last active June 19, 2018 12:57
Show Gist options
  • Save nikkaroraa/fabcf0e9567f1d0bafd60ed779db610f to your computer and use it in GitHub Desktop.
Save nikkaroraa/fabcf0e9567f1d0bafd60ed779db610f to your computer and use it in GitHub Desktop.
Things to clear up before jumping into the world of React

4. How "this" keyword works with functions JS

To access any variable or any method that is a part of a JavaScript object, we use "this" keyword.

For example,

function Dog(name) {
    if (name) { this.name = name; }
    this.speak = function() {
        return this.name + " says woof";
    }
}

Why does it work this way?

Because, whenever we call a particular function (of an object, for instance, obj.speak()), the value of "this" gets replaced by the object that we have specified (obj in this case).

Or you can think of it this way too: You need to use this.propertyName so as to prevent it from colliding with the global variable (that may or may not exist).

By specifying this.propertyName, you make sure that what you are referring to is a property of the current objects (and not some random variable).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment