Heads-up when copying by reference
The fact that objects (including functions and arrays) are copied by reference could sometimes lead to results you don't expect.
Let's create two constructor functions and add properties to the prototype of the first one:
> function Papa() {} >function Wee() {} >Papa.prototype.name = 'Bear'; >Papa.prototype.owns = ["porridge", "chair", "bed"];
Now, let's have Wee
inherit from Papa
(either extend()
or extend2()
will do):
>extend2(Wee, Papa);
Using extend2()
, the Wee
function's prototype inherited the properties of Papa.prototype
as its own:
>Wee.prototype.hasOwnProperty('name'); true >Wee.prototype.hasOwnProperty('owns'); true
The name
property is primitive, so a new copy of it is created. The owns
property is ...
Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.