this in constructor functions

suggest change

When a function is called as a constructor, this is the newly created object. The call without new below is a non-strict script. In strict mode, that call throws because this is undefined. window exists in browsers.

function Cat(name) {
  this.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
window.name; // "Tom"
cat2.name; // error! cannot access property of undefined

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents