Objects
Info:
declare objects with the
const
keyword.JavaScript objects are written with curly braces {}
Objects use named indexes.
The values are written as
name:value pairs
(name and value separated by a colon).const car = {type:"Fiat", model:"500", color:"white"};
Properties
Object properties are written as
name:value pairs
, separated by commas.All cars have the same properties, but the property values differ from car to car.
Methods
All cars have the same methods, but the methods are performed at different times.
Declaration
Info:
You define (and create) a JavaScript object with an object literal:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Danger:
Do Not Declare Strings, Numbers, and Booleans as Objects!
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.
When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
x = new String(); // Declares x as a String object
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Properties
Info:
- JavaScript objects are containers for named values called properties.
The
name:values
pairs in JavaScript objects are called properties:You can access object properties in two ways:
objectName.propertyName
objectName["propertyName"]
Methods
Info:
A method is a function stored as a property.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Accessing Methods
objectName.methodName()
If you access a method without the
()
parentheses, it will return the function definition:name = person.fullName;
// returns: function() { return this.firstName + " " + this.lastName; }
this
this
keyword refers to an objectI.E.
this.firstName
means thefirstName
property ofthis
.I.E.
this.firstName
means thefirstName
property of person.const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};The
this
keyword refers to different objects depending on how it is used- In an object method,
this
refers to the object. - Alone,
this
refers to the global object. - In a function,
this
refers to the global object. - In a function, in strict mode,
this
isundefined
. - In an event,
this
refers to the element that received the event. - Methods like
call()
,apply()
, andbind()
can referthis
to any object.
- In an object method,