Book Image

Object-Oriented JavaScript

By : Stoyan Stefanov, Stoyan STEFANOV
Book Image

Object-Oriented JavaScript

By: Stoyan Stefanov, Stoyan STEFANOV

Overview of this book

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

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';


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')


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


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


Changing B's copy of name doesn...