Object are collections of related data and functionality. We store that functionality in methods on our objects:
const dog = {
dietType: 'omnivores',
makeSound () {
console.log('Wang Wang');
},
diet() {
console.log(dietType);
}
};
dog.makeSound(); // Return 'Wang Wang'
dog.diet(); //Output: "ReferenceError: dietType is not defined"
ReferenceError의 이유: That's because inside the scope of the .diet() method, we don't automatically have access to other properties of the dog object.
-> diet() scope을 벗어나기 때문에 dietType에 접근 할 수 없다.
...
diet() {
console.log(this.dietType);
}
...
console.log(dog.diet()); // Return 'omnivores'
참고 https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
const dog = {
dietType: 'omnivores',
makeSound () {
console.log('Wang Wang');
},
diet: () => {
console.log(this.dietType);
}
};
console.log(dog.diet); // Return undefined
Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object.
In the code snippet above, the value of this is the global object, or an object that exists in the global scope, which doesn’t have a dietType property and therefore returns undefined.
Accessing and updating properties is fundamental in working with objects. However, there are cases in which we don't want other code simply accessing and updating and object's properties. When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value.
Javascript는 privacy를 위한 기능이 없다. 그래서 javascript developers 일반적으로 사용되는 conventions는 (underscore)이다.
해당 property name(key)앞에 를 붙여 privacy를 표시해준다.
const user = {
ID: 'victory',
_password: 1234
};
user._password = 4321;
// ressign 가능함.
Getter are methods that get and return the internal properties of an object. But they can do more than just retrieve the value of a property!
const person = {
_firstName: 'xia',
_lastName: 'Jou',
get fullName() {
if (this._firstName && this._lastName){
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or a last name.';
}
}
};
// To call the getter method:
person.fullName; // 'John Doe'
getter/setter function은 같은 이름을 사용 할 수 없다. 만약 같은 이름을 사용 할 경우 an infinite call stack error가 발생한다.
Along with getter methode, we can also create setter method which reassign valuew of existing properties within an objects.
const person = {
_age: 37,
set age(newAge){
if (typeof newAge === 'number'){
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
person.age = 40;
console.log(person._age); // Logs: 40
person.age = '40';
// Logs: You must assign a number to age
Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used.
Nonetheless, even with a setter method, it is still possible to directrly reassign properties. For example, in the example above, we can still set ._age directly
person._age = 'forty-five'
console.log(person._age); // Prints forty-five
Factory Functions can create many instances of an object quickly.
Factory Function is a function that returns an object and can be reused to make multiple object instances.
Factory Functions can also have parameters allowing us to customize the object that gets returned.
const monsterFactory = (name, age, energySource, catchPhrase) => {
return {
name: name,
age: age,
energySource: energySource,
scare() {
console.log(catchPhrase);
}
}
};
monsterFactory has four parameters and returns an object that has the properties: name, age, energySource, scare()
const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'
To make an object that represents a specific monster like a ghost, we can call monsterFactory with the necessary arguments and assign the return value to a variable.
// truncated version
const monsterFactory = (name, age) => {
return {
name: name,
age: age
}
};
// property value shorthand (ES6)
const monsterFactory = (name, age) => {
return {
name,
age
}
};
We often want o extract key-value pairs from objects and save them as vatiables.
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
//Extract key-valuew pairs
const residence = vampire.residence;
console.log(residence);
// Prints 'Transylvania'
Howevers, we can also take advantage of a destructuring technique called destructured assignments
const { residence } = vampire;
console.log(residence);
// Prints 'Transylvania'
Destructured assingment can grab nested properties of an object
const { day } = vampire.preferences;
console.log(day);
// Prints 'stay inside'
참조 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods