04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: Object-Oriented Programming<br />

The startsWith() method in this example returns true if some given text occurs at the beginning of a<br />

string. The method is assigned to String.prototype , making it available to all strings in the<br />

environment. Since msg is a string, the String primitive wrapper is created behind the scenes, making<br />

startsWith() accessible.<br />

Although possible, it is not recommended to modify native object prototypes in a<br />

production environment. This can often cause confusion and create possible name<br />

collisions if a method that didn ’ t exist natively in one browser is implemented<br />

natively in another. It ’ s also possible to overwrite native methods accidentally.<br />

Problems with Prototypes<br />

The prototype pattern isn ’ t without its faults. For one, it negates the ability to pass initialization<br />

arguments into the constructor, meaning that all instances get the same property values by default.<br />

Although this is an inconvenience, it isn ’ t the biggest problem with prototypes. The main problem comes<br />

with their shared nature.<br />

All properties on the prototype are shared among instances, which is ideal for functions. Properties that<br />

contain primitive values also tend to work well, as shown in the previous example, where it ’ s possible to<br />

hide the prototype property by assigning a property of the same name to the instance. The real<br />

problem occurs when a property contains a reference value. Consider the following example:<br />

function Person(){<br />

}<br />

Person.prototype = {<br />

constructor: Person,<br />

name : “Nicholas”,<br />

age : 29,<br />

job : “Software Engineer”,<br />

friends : [“Shelby”, “Court”],<br />

sayName : function () {<br />

alert(this.name);<br />

}<br />

};<br />

var person1 = new Person();<br />

var person2 = new Person();<br />

person1.friends.push(“Van”);<br />

alert(person1.friends); //”Shelby,Court,Van”<br />

alert(person2.friends); //”Shelby,Court,Van”<br />

alert(person1.friends === person2.friends); //true<br />

Here, the Person.prototype object has a property called friends that contains an array of strings.<br />

Two instances of Person are then created. The person1.friends array is altered by adding another<br />

string. Because the friends array exists on Person.prototype , not on person1 , the changes made are<br />

also reflected on person2.friends (which points to the same array). If the intention is to have an array<br />

165

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!