As a beginner, I am trying to understand the Prototype implementation of Javascript.
I have tried creating object with couple of properties and method.
var obj = {
firstname: 'sampath',
lastname: 'kumar',
fullname: function() {
return `Hi ${this.firstname} ${this.lastname}`
}
}
I am trying to create my own method for firstname
property.
obj.firstname.prototype.sayHi = function() {
return 'Hi';
}
console.log(obj.firstname.sayHi())
Above line throws error as
TypeError: Cannot set property 'sayHi' of undefined
But this one works fine
obj.firstname.__proto__.sayHi = function() { return 'Hi'; }
If we do the same for functions, it's working. Like below
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
I just want to know why obj.firstname.prototype
is not working. And what is the Javascript implementation behind this?