Almost everything in JavaScript can be an Object: Strings, Functions, Arrays, Dates....
Objects are just data, with added properties and methods.
Properties and Methods
Properties are values associated with objects.
Methods are actions objects can perform.
A Real Life Object. A Car:
| Object | Properties | Methods |
|---|---|---|
car.name = Fiat car.model = 500 car.weight = 850kg car.color = white | car.start() car.drive() car.brake() |
The properties of the car include name, model, weight, color, etc.
All cars have these properties, but the property values differ from car to car.
The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods, but they are performed at different times.
| In object oriented languages, properties and methods are often called object members. |
JavaScript Objects
In JavaScript, objects are data (variables), with properties and methods.
Almost "everything" in JavaScript can be objects. Strings, Dates, Arrays, Functions....
You can also create your own objects.
This example creates an object called "person", and adds four properties to it:
Spaces and line breaks are not important. A declaration can span multiple lines:
var person = {
firstName:"John",
lastName :"Doe",
id :5566
};
firstName:"John",
lastName :"Doe",
id :5566
};
There are many different ways to create new JavaScript objects.
You can also add new properties and methods to already existing objects.
You will learn much more about objects later in this tutorial.
Accessing Object Properties
You can access the object properties in two ways:
Accessing Object Methods
You can call a method with the following syntax:
objectName.methodName()
This example uses the fullName() method of a person object, to get the full name:
Object methods are just functions defined as object properties.
You will learn much more about function later in this tutorial.
Did You Know?
| It is common, in object oriented languages, to use camelCase names. You will often see names like someMethod(), instead of some_method(). |
No comments:
Post a Comment