Prototypes in JS

how to access parent method in child scope using prototype

by Samar Pattanayak

JavaScript

function parent() {
  this.name = "samar";
  this.address = "Balasore"
  this.fullNameP = function() {
    console.log("Hi i m from parent")
  }
}
parent.prototype.company = "CTS";
parent.prototype.methodP = function() {
  console.log(`i can access name property ${this.name} and he works in ${this.company}`)
}
var parobj = new parent();
parobj.methodP();

console.log("******child Starts *****")

function child() {
  parent.call(this)
    //this.name="Varun"
  this.age = 23;
  this.salary = 50000;
  this.fullNameC = function() {
    console.log("From parent")
    child.prototype.methodP.call(this);
    //parent.prototype.methodP.call(this);
    console.log("From child")
    console.log(`he gets salary ${this.salary}`)

  }
}

child.prototype = Object.create(parent.prototype); //if i dont mention this line , then  can only access those properties and methods inside parent function not the method/property attached to parent's protoype later

child.prototype.constructor = child;

child.prototype.methodC = function() {
  //parent.prototype.fullNameP.call(this);
}
var childobj = new child();
console.log(`prorty of parent & inherited 2 child ${childobj.address}`);
console.log("******")
childobj.methodP();

console.log("******")
childobj.fullNameC();

console.log("******")
childobj.methodC();

var ao = Object.create(Object.getPrototypeOf(parobj))
var bo = Object.create(Object.getPrototypeOf(childobj))
  //Object.assign({},parobj)

console.log("**** Normal parent object***")
console.log(Object.keys(parobj))
console.log(Object.getOwnPropertyNames(parobj))
console.log(Reflect.ownKeys(parobj))
console.log(Object.getPrototypeOf(parobj))
for (var key in parobj) {
  console.log(`--> ${key}`)
}
console.log(parent.prototype)


console.log("**** Normal child object***")
console.log(Object.keys(childobj))
console.log(Object.getOwnPropertyNames(childobj))
console.log(Reflect.ownKeys(childobj))
console.log(Object.getPrototypeOf(childobj))
for (var key in childobj) {
 ...