What is the reason to use the 'new' keyword at Derived.prototype = new Base

后端 未结 6 1707
甜味超标
甜味超标 2020-11-21 05:27

What does the following code do:

WeatherWidget.prototype = new Widget;

where Widget is a constructor, and I want to extend the

6条回答
  •  梦如初夏
    2020-11-21 05:35

    In plain english you're extending one class with another. A prototype can only be an object so you set WeatherWidget's prototype to a new instance of Widget. If you removed the new keyword you would be setting the prototype to the literal constructor function which doesn't do anything.

    var Appendages = function(){
      this.legs = 2
    };
    var Features = function() {
       this.ears = 4;
       this.eyes = 1;
    }
    
    // Extend Features class with Appendages class.
    Features.prototype = new Appendages;
    var sara = new Features();
    sara.legs;
    // Returns 2.
    

    Understanding that the prototype can be any object, something like this would also work:

    var appendages = {
      legs : 2
    };
    var Features = function() {
       this.ears = 4;
       this.eyes = 1;
    }
    
    // Extend Features class with Appendages class.
    Features.prototype = appendages;
    var sara = new Features();
    sara.legs;
    // Returns 2.
    

    In JavaScript, if the key isn't found on the object, it checks the parents object you extended it from. Hence you can change items on the parent object on the fly like so:

    var appendages = {
      legs : 2
    };
    var Features = function() {
       this.ears = 4;
       this.eyes = 1;
    }
    
    // Extend Features class with Appendages class.
    Features.prototype = appendages;
    var sara = new Features();
    sara.legs;
    // Returns 2.
    appendages.hair = true;
    sara.hair;
    // Returns true.
    

    Note that this all happens during instantiation which means you can't just switch out the prototype after you've created the object:

    var foo = {name : 'bob'};
    var bar = {nachos : 'cheese'};
    foo.prototype = bar;
    foo.nachos;
    // undefined
    

    However, all modern browsers come with this newer __proto__ method, which allows you to do it:

    var foo = {name : 'bob'};
    var bar = {nachos : 'cheese'};
    foo.__proto__ = bar;
    foo.nachos
    // "cheese"
    

    Read up more on understanding JavaScript prototypes here. This article from Pivotal Labs is also really good.

提交回复
热议问题