Is there any difference between the following two methods of inheriting objects in Javascript?
function Person(name) {
this.name = name;
}
function Student(name, id) {
Person.call(this, name);
this.id = id;
}
Method 1:
Student.prototype.__proto__ = Person.prototype;
Method 2:
Student.prototype = new Person;
Student.prototype.constructor = Student;
Besides creation of objects by specified pattern, a constructor function does another useful thing, it automatically sets a prototype object for newly created objects. This prototype object is stored in the
ConstructorFunction.prototypeproperty.You can explicitly do that by setting the, pretty much “internal”,
.__proto__property to a specific object. That is not possible in all javascript implementations anyway. But basically, its pretty much the same.If the prototype is not set specifically for an object, the default object is taken (
Object.prototype).