Why is it necessary to set the prototype constructor?

前端 未结 14 1748
孤城傲影
孤城傲影 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:20

    I'd disagree. It isn't necessary to set the prototype. Take that exact same code but remove the prototype.constructor line. Does anything change? No. Now, make the following changes:

    Person = function () {
        this.favoriteColor = 'black';
    }
    
    Student = function () {
        Person.call(this);
        this.favoriteColor = 'blue';
    }
    

    and at the end of the test code...

    alert(student1.favoriteColor);
    

    The color will be blue.

    A change to the prototype.constructor, in my experience, doesn't do much unless you're doing very specific, very complicated things that probably aren't good practice anyway :)

    Edit: After poking around the web for a bit and doing some experimentation, it looks like people set the constructor so that it 'looks' like the thing that is being constructed with 'new'. I guess I would argue that the problem with this is that javascript is a prototype language - there is no such thing as inheritence. But most programmers come from a background of programming that pushes inheritence as 'the way'. So we come up with all sorts of things to try and make this prototypical language a 'classic' language.. such as extending 'classes'. Really, in the example they gave, a new student is a person - it isn't 'extending' from another student.. the student is all about the person, and whatever the person is the student is as well. Extend the student, and whatever you've extended is a student at heart, but is customized to fit your needs.

    Crockford is a bit crazy and overzealous, but do some serious reading on some of the stuff that he's written.. it'll make you look at this stuff very differently.

提交回复
热议问题