Do you need a constructor every time you implement prototypal inheritance ?๐Ÿค”๐Ÿ’ญ

Do you need a constructor every time you implement prototypal inheritance ?๐Ÿค”๐Ÿ’ญ

ยท

1 min read

Well the answer is NO.

Hey there ! Welcome back to another read.

It is possible in Javascript to manually implement prototypal inheritance. Well how ?Lets look at the code below.

//object literal (prototype)
const empProto = {
  setEmpLocation(location) {
    this.location = location;
  },
};

In the usual prototypal inheritance we have seen how objects have the inherent __proto__ property when they are created. Using the Object.create() we can manually create prototype object.

//creating an object with prototype object
const lucas = Object.create(empProto);
lucas.empId = 200;
lucas.empName = 'Lucas';
lucas.setEmpLocation('Australia');

As you can see , lucas object now has a prototype property. Lets verify the same.

console.log(lucas.__proto__ === empProto);//return true

Until the next one ,Break,Code,Repeat! ๐Ÿ˜‰

ย