In real life, a car is an object.
The car has functions such as: start, drive, stop and properties such as: weight, color and model.
Object | Properties | Functions |
---|---|---|
CAR | car.brand = BMW car.model = 420d car.weight = 1475kg car.color = black |
car.start() car.drive() car.break() car.stop() |
All cars have similar characteristics however, property values vary from car to car. All cars have similar functions.
Objects
JavaScript variables are used to store data.
In the example, a single value (BMW) is assigned to the variable named car
.
var car = "BMW";
Objects are mutable. However, objects can take more than one value.
In the example, more than one value (BMW, 420d, black) is assigned to the variable named car
.
var car = {brand: "BMW", model: "420d", color: "black"};
JavaScript object declaration is done as
name: value
.
Object properties
JavaScript
name: value
pairs are called properties.
var me = {name: "Baransel", surname: "ARSLAN", age: 22};
Property | Value |
---|---|
name |
Baransel |
surname |
Arslan |
age |
22 |
Object functions
Object functions operate inside the object.
JavaScript object functions are stored as functions in object properties.
var me = {
name: "Baransel",
surname: "ARSLAN",
age: 22,
fullName: function() {
return this.name + " " + this.surname;
}
};
You can call the function with the following syntax:
var me = {
name: "Baransel",
surname: "ARSLAN",
age: 22,
fullName: function() {
return this.name + " " + this.surname;
}
};
me.fullName();
// Output: Baransel ARSLAN