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

后端 未结 6 1733
甜味超标
甜味超标 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:39

    new is important for prototype inheritance; i.e.
    Create a constructor with a method

    var Obj = function(){};
    Obj.prototype = {};
    Obj.prototype.foo = function(){console.log('foo');};
    

    Make a second constructor to extend the first with

    var ExObj = function(){};
    

    Now, if we prototype without new,

    ExObj.prototype = Obj;
    (new ExObj).foo(); // TypeError: Object # has no method 'foo'
    
    
    

    Which means we haven't inherited from the prototype of Obj, however, if we prototype with new

    ExObj.prototype = new Obj();
    (new ExObj).foo(); // console logs 'foo'
    

    Furthermore, adding new things to the prototype of ExObj doesn't make any changes to it's base, Obj.

    提交回复
    热议问题