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

后端 未结 6 1743
甜味超标
甜味超标 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:52

    WeatherWidget.prototype = new Widget;
    

    does create a new instance of the Widget constructor and use it as WeatherWidget's prototype object. Using the new keyword creates the new object, sets up the inheritance chain of it to Widget.prototype, and applies the constructor function on it (where you can set up individual properties'n'methods, or create private-scoped variables).

    Without the new keyword it would be an assignment of the Widget function to the prototype property - which does not make any sense. If you'd add the optional brackets (i.e. Widget()), it would invoke the function normally, but not as a constructor on a new instance, but with the global object as context. See also the reference for the this keyword.

    Notice that you should not really use this code. As said, it creates a new instance by invoking the constructor function. But the purpose is only to create an empty object that inherits from the Widgets prototype object, not to instantiate something (which could do some harm, depending on the code). Instead, you should use Object.create (or its popular shim):

    WeatherWidget.prototype = Object.create(Widget.prototype);
    

    see also Javascript basic inheritance vs Crockford prototypical inheritance

提交回复
热议问题