JavaScript Object
JavaScript Object
Object Properties
A real life car has properties like weight and
color:
car.name = Fiat, car.model = 500, car.weight =
850kg, car.color = white.
Car objects have the same properties, but
the values differ from car to car.
Object Methods
A real life car has methods like start and stop:
car.start(), car.drive(), car.brake(), car.stop().
Car objects have the same methods, but the
methods are performed at different times.
<script>
// Create an Object:
const person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
// Display Data from the Object:
document.getElementById("demo").innerHT
ML =
person.firstName + " is " + person.age + "
years old.";
</script>
Spaces and line breaks are not important. An
object initializer can span multiple lines:
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Example:
<script>
// Create an Object
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Object Properties
he named values, in JavaScript objects, are
called properties.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Or
// Display lastName from the Object:
document.getElementById("demo").inner
HTML =
"The last name is " + person["lastName"];
Example
<script>
// Constructor Function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
var myFather = new Person("John", "Doe",
50, "blue");
// Display age
document.write("My father is "
+myFather.age + ".");
</script>
<script>
// Display age
document.getElementById("demo").inner
HTML =
"My father is " + myFather.age + ". My
mother is " + myMother.age + ".";
</script>