I create a constructor for "car" and then create two cars, one using the "new" keyword, the other using "Object.create"
function car (name) {
this.name=name
}
let car1 = new car("volvo")
let car2 = Object.create(car.prototype)
car2.name = "hyundai"
BTW: is it possible to set attributes immediately with "Object.prototype" like it is done with "new"? (so I wouldn't have to use the next line 'car2.name = "hyundai"')
If I then set a ".honk()" method to "car.prototype", it works for both "car1" and "car2":
car.prototype.honk= function (){
return `${this.name}'s honk`
}
However, if I define the ".honk()" method within the "car" constructor, then "car1" is able to use it, but "car2" is not! Why?
function car (name) {
this.name=name
this.honk = function(){
return `${this.name}'s honk`;
}
}