Objects
Info:
declare objects with the
constkeyword.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:valuespairs in JavaScript objects are called properties:You can access object properties in two ways:
objectName.propertyNameobjectName["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
thiskeyword refers to an objectI.E.
this.firstNamemeans thefirstNameproperty ofthis.I.E.
this.firstNamemeans thefirstNameproperty of person.const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};The
thiskeyword refers to different objects depending on how it is used- In an object method,
thisrefers to the object. - Alone,
thisrefers to the global object. - In a function,
thisrefers to the global object. - In a function, in strict mode,
thisisundefined. - In an event,
thisrefers to the element that received the event. - Methods like
call(),apply(), andbind()can referthisto any object.
- In an object method,