Our definition: Instantiation in OOP is a process of creating an object from a given structure/blueprint(constructor).
We use the new
keyword to create an instance
new World();
What does the new
keyword do?
- Tells Js engine that the function is not a regular function but
a constructor therefore create a blank object called the
this
object. - Injects the constructor prototype into the
this
object to make the prototype fields accessible by the constructor instance. - Returns
this
object if the constructor doesn't return an explicit object.
function Country(name) {
this.name = name;
this.defaultGreeting = "Hello!"
this.greet = function () {
if (this.name === "Estonia") return "Tere!";
return this.defaultGreeting;
};
}
const estonia = new Country("Estonia");
console.log("Estonia says", estonia.greet());
const germany = new Country("Germany");
console.log("Germany says", germany.greet());