What does the following code do:
WeatherWidget.prototype = new Widget;
where Widget
is a constructor, and I want to extend the
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 Widget
s 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