0

what is different between Object.create(functionname.prototype) vs new Student() constructor call.

function Student(name){
    this.name = name;
}
 function UniversityStudent(id){
    this.id= id;
}


// 1st way
UniversityStudent.prototype = Object.create(Student.prototype);
var std = new UniversityStudent(123);
// but I cannot access std.name why ?

// 2nd way
UniversityStudent.prototype = new Student("Lasith Malinga");
var std1 = new UniversityStudent(123);
// When I use std1.name now then it can

When I use 1st way then I cannot access Student`s object properties, but I use 2nd way it can, What is difference. I think both way are same... Is it wrong ?

Sachintha Udara
  • 635
  • 1
  • 7
  • 22

1 Answers1

2

The reason why you can't access std.name is because you are not doing the Student constructor from the UniversityStudent constructor.

You do extend Student successfully with this line:

UniversityStudent.prototype = Object.create(Student.prototype);

But when you instantiate it you must do Student.call(this, name)

Like this

function Student(name){
this.name = name;
}
function UniversityStudent(id, name){
  Student.call(this, name);
  this.id= id;
}

Take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Jaime Liz
  • 136
  • 1
  • 4
  • Thank You...... :D – Sachintha Udara May 18 '17 at 17:50
  • no problem, make sure to checkout the Inheritance and Prototype Chain page on the MDN, it explains a lot of quirks in the prototype model. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain – Jaime Liz May 18 '17 at 19:07