JavaScript Objects
- JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own.
- An object is just a special kind of data, with a collection of properties and methods.
Person Object:
- Properties are: name, height, weight, age, skin tone, eye color, etc.
- Methods are: eat(), sleep(), work(), play(), etc.
Accessing object properties or methods:
Add properties to an object by simply giving it a value:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname); |
John |
Call an Object Methods
Creating Your Own Objects
There are different ways to create a new object:
1. Create a direct instance of an object
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue"; |
Adding a method to the personObj following code adds a method called eat() to the personObj:
2. Create a template of an object
The template defines the structure of an object:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
} |
This template is just a function. This is instance of current object.
Create a new instance using the template:
myFather=new person("John","Doe",50,"blue");
myMother=new person("Sally","Rally",48,"green"); |
Add Methods inside the template:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.newlastname=newlastname;
} |
- Methods are just functions attached to objects.
newlastname() function:
function newlastname(new_lastname){this.lastname=new_lastname;} |
You can write: myMother.newlastname("Doe"). |