1

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?

Gopalakrishnan T
  • 453
  • 1
  • 4
  • 14
  • `TypeError: Cannot set property 'toLowerCase' of undefined` there is no `toLowerCase` in your code? – VLAZ Oct 04 '19 at 16:08
  • Updated the code. Please do check now. – Gopalakrishnan T Oct 04 '19 at 16:10
  • https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript – Chris Li Oct 04 '19 at 16:12
  • 2
    *"I just want to know why `obj.firstname.prototype`"* Because `firstname` is a string, and strings don't have a property called `prototype`. They *do* (on browsers) have a property called `__proto__`, which is a reference to `String.prototype`, but not one called `prototype`. The `prototype` property is a function thing: For function `F`, `F.prototype` refers to the object that will be the prototype of a new object created via `new F`. – T.J. Crowder Oct 04 '19 at 16:13
  • 1
    About `__proto__`: Avoid it. It's a backward-compatibility hack and isn't present for all objects. Instead, if you want the prototype of an object, use `Object.getPrototypeOf`. – T.J. Crowder Oct 04 '19 at 16:14
  • @T.J.Crowder Thanks for the clarification. – Gopalakrishnan T Oct 04 '19 at 16:25

0 Answers0