- Continued.
- Here's the Dog constructor from the previous post:
function Dog() {
this.name = "Anakin";
this.color = "brown";
this.numLegs = 4;
}
let hound = new Dog();
NOTE: this
inside the constructor always refers to the object being created.
- Notice that the
new
operator is used when calling a constructor. This tells JavaScript to create a new instance ofDog
calledhound
. Without thenew
operator, this inside the constructor would not point to the newly created object, giving unexpected results. Nowhound
has all the properties defined inside theDog
constructor:
hound.name; // when console.log it will print out Anakin
hound.color; // when console.log it will print out brown
hound.numLegs; // whem console.log it will print out 4
- Just like any other object, its properties can be accessed and modified:
hound.name = 'Obi-Wan Kenobi';
console.log(hound.name); // will print out Obi-Wan Kenobi
Top comments (0)