2

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;
1
  • 1
    I don't think setting the constructor attribute is of any use. Commented Oct 16, 2011 at 3:00

1 Answer 1

1

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.prototype property.

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.