Why is it necessary to set the prototype constructor?

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

    No need for sugared function 'classes' or using 'New' these days. Use object literals.

    The Object prototype is already a 'class'. When you define an object literal, it is already an instance of the prototype Object. These can also act as another object's prototype, etc.

    const Person = {
      name: '[Person.name]',
      greeting: function() {
        console.log( `My name is ${ this.name || '[Name not assigned]' }` );
      }
    };
    // Person.greeting = function() {...} // or define outside the obj if you must
    
    // Object.create version
    const john = Object.create( Person );
    john.name = 'John';
    console.log( john.name ); // John
    john.greeting(); // My name is John 
    // Define new greeting method
    john.greeting = function() {
        console.log( `Hi, my name is ${ this.name }` )
    };
    john.greeting(); // Hi, my name is John
    
    // Object.assign version
    const jane = Object.assign( Person, { name: 'Jane' } );
    console.log( jane.name ); // Jane
    // Original greeting
    jane.greeting(); // My name is Jane 
    
    // Original Person obj is unaffected
    console.log( Person.name ); // [Person.name]
    console.log( Person.greeting() ); // My name is [Person.name]
    

    This is worth a read:

    Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

    ...

    A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties

提交回复
热议问题