JavaScript this in constructor functions


When using a function as a constructor, it has a special this binding, which refers to the newly created object:

function Cat(name) { = name;
  this.sound = "Meow";

var cat = new Cat("Tom"); // is a Cat object
cat.sound; // Returns "Meow"

var cat2 = Cat("Tom"); // is undefined -- function got executed in global context; // "Tom"; // error! cannot access property of undefined