Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

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 some properties to the prototype of the first one:

>>> var A = function(){}, B = function(){};
>>> A.prototype.stuff = [1,2,3];

[1, 2, 3]

>>> A.prototype.name = 'a';

"a"

Now let's have B inherit from A (either extend() or extend2() will do):

>>> extend2(B, A);

Using extend2(), B's prototype inherited A.prototype's properties as own properties.

>>> B.prototype.hasOwnProperty('name')

true

>>> B.prototype.hasOwnProperty('stuff')

true

The name property is primitive so a new copy of it is created. The property stuff is an array object so it is copied by reference:

>>> B.prototype.stuff

[1, 2, 3]

>>> B.prototype.stuff === A.prototype.stuff

true

Changing B's copy of name doesn...