Skip to content

Instantly share code, notes, and snippets.

@themoxman
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save themoxman/9393769 to your computer and use it in GitHub Desktop.
Save themoxman/9393769 to your computer and use it in GitHub Desktop.

ELOQUENT JS -- CONTENTS

new

Just like the notation with braces and colons we have already seen, new is a way to create object values. Instead of specifying all the property names and values, a function is used to build up the object. This makes it possible to define a kind of standard procedure for creating objects. Functions like this are called constructors, and in chapter 8 we will see how to write them.

new

The new keyword provides a convenient way of creating new objects. When a function is called with the word new in front of it, its this variable will point at a new object, which it will automatically return (unless it explicitly returns something else). Functions used to create new objects like this are called constructors. Here is a constructor for rabbits:

function Rabbit(adjective) {
  this.adjective = adjective;
  this.speak = function(line) {
    print("The ", this.adjective, " rabbit says '", line, "'");
  };
}

var killerRabbit = new Rabbit("killer");
killerRabbit.speak("GRAAAAAAAAAH!");

It is convention to start the names of constructors with a capital letter. This makes it easy to distinguish them from other functions.

Why is the new keyword even necessary?

Prototype and Constructor properties

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