I probably did not make the title correctly but please someone explain why I can't create prototype for person object? Only works when I put hit to Object.prototype chain.
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
//person.prototype.hit = function(){
// console.log("hitting me");
//}
Object.prototype.hit = function(){
console.log("hitting me");
}
const me = Object.create(person);
me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten
me.printIntroduction();
me.hit();
(UPDATE) . Why does THIS work?? Not sure what the differences are actually from this example but this code works.
function person {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
}();
person.prototype.hit = function(){
console.log("hitting me");
}
/*
person.prototype.hit = function(){
console.log("hitting me");
}
*/
Object.prototype.hit = function(){
console.log("hitting me");
}
const me = Object.create(person);
me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten
me.printIntroduction();
me.hit();
// expected output: "My name is Matthew. Am I human? true"
update 2
Ok, so I make it work like below but clearly prototype doesn't work the way I expected.. so I am clearly confused about prototype
function person(){
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
person.prototype.hit = function(){
console.log("hitting me1");
}
Object.prototype.hit = function(){
console.log("hitting me2");
}
const me = Object.create(person);
me.hit();
UPDATE 3.
thank you.. this is the explanation that I got from below.. thank you and this is clear now.
function person(){
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
person.prototype.hit = function(){
console.log("hitting me1");
}
Object.prototype.hit = function(){
console.log("hitting me2");
}
//const me = Object.create(person);
const me = new person;
me.hit();