Why is it necessary to set the prototype constructor?

前端 未结 14 1983
孤城傲影
孤城傲影 2020-11-22 02:54

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:

// correct the          


        
14条回答
  •  不要未来只要你来
    2020-11-22 03:27

    This has the huge pitfall that if you wrote

    Student.prototype.constructor = Student;
    

    but then if there was a Teacher whose prototype was also Person and you wrote

    Teacher.prototype.constructor = Teacher;
    

    then the Student constructor is now Teacher!

    Edit: You can avoid this by ensuring that you had set the Student and Teacher prototypes using new instances of the Person class created using Object.create, as in the Mozilla example.

    Student.prototype = Object.create(Person.prototype);
    Teacher.prototype = Object.create(Person.prototype);
    

提交回复
热议问题