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

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

    According to some odd Javascript rules, new Widget actually invokes the constructor rather than returning a reference to the constructor. This question actually answers the question the difference between var a = new Widget() and var a = Widget().

    In simple words, the new keyword tells Javascript to call the function Widget under a different set of rules than a regular function call. Going off the top of my head, the ones I remember are:

    1. There is a brand new object created
    2. Widget can use the this keyword to refer to that object.
    3. If Widget does not return anything, this new object will be created.
    4. This object will inherit a few additional properties that will indicate it was created by Widget that are used to track down property chains.

    Without the new keyword, a call to widget would

    1. If in strict mode, this will be set to undefined.
    2. Otherwise, this will refer to the global object. (Called window by the browser.)
    3. If the function does not return anything, then undefined will be returned.

    Reference: new keyword

提交回复
热议问题