ShankarGuru
ShankarGuru

Reputation: 625

Clarifications on prototypal inheritance

I have a prototypal inheritance like below where Student extends Guru. I have three questions, can someone clarify the same.

function Guru(name){
  this.name = name;
}

Guru.prototype.copy = function(){
  return this.constructor(this.name);
}

function Student(name){
  Guru.call(this)
  this.name = name;
}

Student.prototype = Object.create(Guru.prototype);
Student.prototype.constructor = Student;
var stu = new Student("John Cena");

console.log(stu.constructor);
console.log(stu.__proto__);
  1. Why should we avoid Student.prototype = new Guru();
  2. What is the difference between these two:

    console.log(stu.constructor);
    console.log(stu.__proto__);
    

    Prints the below:

    [Function: Guru]
    Guru { constructor: [Function: Student] }
    
  3. Difference between constructor.prototype and prototype.constructor? Do we have constructor.prototype in javascript?

Upvotes: -1

Views: 44

Answers (1)

Oriol
Oriol

Reputation: 287980

  1. Why should we avoid Student.prototype = new Guru()?

Because Guru constructor expects an instance, not a subclass. Properties created in that constructor should be assigned directly to the instance.

In your case it doesn't matter much, but imagine this:

function C1() { this.o = []; }
function C2() {}
C2.prototype = new C1();
var c1a = new C1(), c1b = new C1(),
    c2a = new C2(), c2b = new C2();
c1a.o.push(123);
c2a.o.push(456);
c1b.o; // []    -- The property is NOT shared among C1 instances
c2b.o; // [456] -- The property is shared among all Sub instances
  1. What is the difference between stu.constructor and stu.__proto__?

When you create the Student constructor, it receives automatically a prototype with a constructor property which points back to Student.

Instead , __proto__ is a getter which returns the [[Prototype]] of an object. Note this is not much standard (it's only defined in an annex for browsers), you should use Object.getPrototypeOf instead.

Therefore, stu.constructor (inherited from Student.prototype) is Student. And stu.__proto__ (inherited from Object.prototype) is Student.prototype.

  1. Difference between constructor.prototype and prototype.constructor?

Using constructor.prototype on a prototype is pointless because it gives the same prototype (assuming it has not been altered).

Using constructor.prototype on a instance gives the prototype it inherits from (assuming it is not shadowed nor has been altered).

Using prototype.constructor on a constructor is pointless because it gives the same constructor (assuming it has not been altered).

Upvotes: 1

Related Questions