Skip to content

Instantly share code, notes, and snippets.

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

2. How "new" keyword works in JS

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

  var v = new Dog("Vincent");

When we call the Dog function with the new keyword we are asking JavaScript to do three things:

  1. Create an empty object;
  2. Set the new object's prototype to point to the Dog.prototype;
  3. And call the constructor method on the new object.
  var v = Object.create(Dog.prototype);
  v.constructor("Vincent");

  v.speak();  // "Vincent says woof"

The first line above creates an empty object and sets its prototype to equal the first argument, in this case Dog.prototype. The second line simply executes the constructor method on the object, which now points to the Dog function.

If you want to go more in depth, please refer to this!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment