JavaScript Objects JAVASCRIPT
- JavaScript Introduction
- JavaScript Syntax
- JavaScript innerHTML
- JavaScript document.write()
- Javascript - window.alert()
- JavaScript - console.log()
- JavaScript Comments
- JavaScript Variables
- JavaScript Operators
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Conditions
- JavaScript Switch
- JavaScript Loop For
- JavaScript While Loop
- JavaScript Break and Continue
- JavaScript Type Conversion
- JavaScript Errors
- JavaScript Scope
- JavaScript this Keyword
- JavaScript Classes
- JavaScript Debugging
- JavaScript - Changing CSS
- JavaScript JSON
JavaScript Objects
JavaScript Objects
Real-Life Objects, Properties, and Methods
In real life, a car is an object. A car has properties like weight and color, and methods like start and stop:
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Tesla) to a variable named car:
Objects are variables too. But objects can contain many values.
This code assigns many values (Tesla , Cybertruck , white) to a variable named car:
Object Definition
You define (and create) a JavaScript object with an object literal:
Spaces and line breaks are not important. An object definition can span multiple lines:
firstName: "Deepak",
lastName: "Chahar",
age: 22,
eyeColor: "blue"
};
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
Object Methods
Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.
firstName: "Deepak",
lastName : "Chahar",
id : 2121,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword
In a function definition, this
refers to the "owner" of the function.
In the example above, this
is the person object that "owns" the fullName
function.
In other words, this.firstName
means the firstName
property of this object.
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
Example
name = person.fullName();
If you access a method without the () parentheses, it will return the function definition:
name = person.fullName;