Objects (1)
이 글은 자바스크립트의 Objects(객체)에 관한 개념 및 문법을 정리하기 위해 작성하였습니다.
< Objects >
We can use JavaScript objects to model real-world things, like a basketball, or we can use objects to build the data structures that make the web possible.
JavaScript objects are containers storing related data and functionality.
< Creating Object Literals >
To create a Object.
let object = {
'key' : value,
key : value
}
- Objects can be assigned to variables just like any Javascript type. To designate an Object Literal, use { }
- We fill an object with unordered data. This data is organized into key-value pairs.
1. key : 'String', can omit ' ' when have not any special characters in it.
2. value : any data
< Accessing Properties >
To access the object's property.
A property is what an object has, while a method is what an object does.
1. Dot Notation : . (dot)
object.propertyName // propertyName is key
ex)
let spaceship = {
homePlanet: 'Earth',
color: 'silver'
};
spaceship.homePlanet; // 'Earth'
spaceship.color; // 'silver'
2. Bracket Notation : [ ]
object['property name'] // property name is key
- Must use when the key has special characters.
- You can also use a variable inside [ ] (expecially with function).
ex)
let spaceship = {
homePlanet: 'Earth',
color: 'silver'
};
let returnAnyPro = (object, property) => {
objectp[property];
}
returnAnyPro(spaceship, homePlanet); // 'Earth'
- If we try to access a property that does not exist, undefined will be returned.
< Property Assignment >
To update a object's property after we create it.
1. Replace or Add
ex)
const spaceship = {
type: 'shuttle'
};
spaceship.color = 'gold'; // Creates a new key of 'color' with a value of 'gold'
- if there was no property with the name, a new property will be added to the object.
2. Delete
ex)
const spaceship = {
'Fuel Type': 'Turbo Fuel',
homePlanet: 'Earth',
mission: 'Explore the universe'
};
delete spaceship.mission; // Removes the mission property
- It's important to know that although we can't reassign an object declared with const, we can still mutate it.
< Methods >
When the data stored on an object is a function, we call that a method
A property is what an object has, while a method is what an object does.
1. Include Method
let object = {
key: function() {
// code block
}
}
// With the new method syntax introduced in ES6 we can omit the colon and the function keyword.
let object = {
key () {
// code block
}
}
2. Invoke Method
object.key(); // Invoke the object's key function
ex)
const alienShip = {
invade () {
console.log('Hello! We have come to dominate your planet.')
}
};
alienShip.invade(); // 'Hello! We have come to dominate your planet.'
+. console is a global javascript object and .log() is a method on that object.
Math is also a global javascript object and .floor() is a method on it.
< Nested Objects >
an object can have another object as a property.
ex)
const spaceship = {
telescope: {
yearBuilt: 2018,
model: '91031-XLT',
focalLength: 2032
},
crew: {
captain: {
name: 'Sandra',
degree: 'Computer Engineering',
encourageTeam() { console.log('We got this!') }
}
},
nanoelectronics: {
computer: {
terabytes: 100,
monitors: 'HD'
},
'back-up': {
battery: 'Lithium',
terabytes: 50
}
}
};
// Access the spaceship's property
spaceship.nanoelectronics['back-up'].battery; // 'Lithium'
< Pass By Reference >
Objects are passed by reference. This means when we pass a variable assigned to an object into a function as an argument, the computer interprets the parameter name as pointing to the space in memory that holding that object.
As a result, function which change object's properties actually mutate the object.
ex)
const spaceship = {
homePlanet : 'Earth',
color : 'silver'
};
let paintIt = obj => {
obj.color = 'glorious gold'
};
paintIt(spaceship);
spaceship.color; // 'glorious gold'
However, reassignment of the object in a function wouldn't work.
ex)
let spaceship = {
homePlanet : 'Earth',
color : 'red'
};
let tryReassignment = obj => {
obj = {
identified : false,
'transport type' : 'flying'
}
console.log(obj) // Prints {'identified': false, 'transport type': 'flying'}
};
tryReassignment(spaceship); // The attempt at reassignment does not work.
spaceship; // Still returns {homePlanet : 'Earth', color : 'red'};
spaceship = {
identified : false,
'transport type': 'flying'
}; // Regular reassignment still works.
- obj : reference to the location of the spaceship object.
(not to spaceship variable, because obj is a variable in its own right)
-> obj is a variable, and its value is spaceship object's memory (at first).
But later, its value is { identified : false, 'transport type' : 'flying' }
< Looping Through Object : for... in >
To execute a given block of code for each property in an object.
ex)
let spaceship = {
crew: {
captain: {
name: 'Lily',
degree: 'Computer Engineering',
cheerTeam() { console.log('You got this!') }
},
'chief officer': {
name: 'Dan',
degree: 'Aerospace Engineering',
agree() { console.log('I agree, captain!') }
},
medic: {
name: 'Clementine',
degree: 'Physics',
announce() { console.log(`Jets on!`) } },
translator: {
name: 'Shauna',
degree: 'Conservation Science',
powerFuel() { console.log('The tank is full!') }
}
}
};
// for...in
for (let crewMember in spaceship.crew) {
console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
}
// captain: Lily
// chief officer: Dan
// medic: Clementine
// translator: Shauna
- for... in will iterate each element of the spaceship.crew object.
in each iteration, the variable crewMember is set to one of the spaceship.crew's keys