JavaScript Object
Object is just a special data type and has a series of properties and methods. Let us use an example to understand: a person is an object. Properties are values associated with objects. A person's attributes include his or her name, height, weight, age, skin color, eye color, etc. All people have these attributes, but the values of the attributes are different for each person. Objects also have methods. Methods are behaviors that can be applied to objects. People's methods may be eating, sleeping, working, playing, etc.
Properties
Methods to access the properties of an object:
objectname.property
You can add properties to an object by simply assigning a value to the property. Assume that the personObj object exists - you can add properties such as firstname, lastname, age, and eyecolor.
personObj.firstname="John" personObj.lastname="Doe" personObj.age=30 personObj.eyecolor="blue" document.write(personObj.firstname)
The above code generates the following output:
John
Methods
Objects can contain methods.
Use the following syntax to call a method:
Object name.Method name ()
Note: The parameters for the method between the brackets can be omitted.
Call the method of the personObj object named sleep:
personObj.sleep()
Create your own object
There are many different ways to create objects:
1. Create an instance of the object
The following code An instance of the object is created and four properties are added to it:
personObj=new Object() personObj.firstname="John" personObj.lastname="Doe" personObj.age=50 personObj.eyecolor="blue"
Adding methods to personObj is also very simple. The following code adds a method named eat() to personObj:
personObj.eat=eat
2. Create a template for the object
The template defines the structure of the object.
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname this.lastname=lastname this.age=age this.eyecolor=eyecolor }
Note: The template is just a function. You need to assign content to this.propertiName inside the function.
Once you have the template, you can create new instances like this:
myFather=new person("John","Doe",50,"blue") myMother=new person("Sally","Rally ",48,"green")
You can also add certain methods to the person object. And it also needs to be operated within the template:
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname this.lastname=lastname this.age=age this.eyecolor=eyecolor this.newlastname=newlastname }
Note: Methods are just functions attached to objects. Then, we need to write the newlastname() function:
function newlastname(new_lastname) { this.lastname=new_lastname }
Newlastname() function defines the new lastname of person and assigns it to person. By using "this.", JavaScript knows who you are referring to. So now you can write: myMother.newlastname("Doe").