this in constructor functions
suggest changeWhen 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents