JavaScript e Ajax

Page 169

Chapter 27: Create Your Own Objects with JavaScript </body> </html>

Figure 27.2

After you have the template, you can create new instances of the object, like this: myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green");

You can also add some methods to the person object. This is also done inside the template: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; }

Note that methods are just functions attached to objects. Then you will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname; }

The newlastname() function defines the person’s new last name and assigns that to the person. JavaScript knows which person you’re talking about by using “this.” So, now you can write: myMother.newlastname("Doe").

155


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.