Declaring a constructor function
suggest changeA constructor is a function meant to be called with new. new creates an object and binds it to this, and that object is the result unless the function returns some other object.
function Cat(name) {
this.name = name;
this.sound = "Meow";
}
Constructor functions are invoked using the new keyword:
const cat = new Cat("Tom");
cat.sound; // Returns "Meow"
Constructor functions also have a prototype property which points to an object whose properties are automatically inherited by all objects created with that constructor:
Cat.prototype.speak = function() {
console.log(this.sound);
}
cat.speak(); // Outputs "Meow" to the console
Objects created by constructor functions also have a special property on their prototype called constructor, which points to the function used to create them:
cat.constructor // Returns the `Cat` function
Objects created by constructor functions are also considered to be “instances” of the constructor function by the instanceof operator:
cat instanceof Cat // true (a boolean, not the string "true")
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents