const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet();
// Output: herbivore
함수를 객체인goat
의 method로서 사용했다. 이런 경우, this는 해당 object의 property에 접근 할 수 있게 해준다.
arrow function 에서 this 는 상위 scoope를 가리킨다. (Lexical this)
const goat = {
name: 'Billy',
color: 'biege',
giveDetails(){
console.log(`${this.name} is a ${this.color} goat.`)
}, // method 작성법 1 (shorthand format)
giveDetails: function() {
console.log(`${this.name} is a ${this.color} goat.`)
} // method 작성법 2 (longhand format)
}
const person = {
_firstName: 'John',
_lastName: 'Doe',
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'
인수가 없고, 객체 내부 property를 읽을 때 사용함.
함수처럼 호출하지 않고, 객체의 일반 property들에 접근하는 것 처럼 평범하게 objName.getmethodName(person.fullName
)처럼 사용함.
getter는 조건문을 사용해서 다른 값을 리턴 할 수 있다.
_(underscore) 사용 이유는 내부에서만 사용할 변수나 함수일때 붙인다.(private) (그냥 관습같은 것임)
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
인수가 하나 있고, property 에 값을 쓸때 사용한다.
getter 처럼 method 호출할때 괄호 필요 없다.
const monsterFactory = (name, age, energySource, catchPhrase) => {
return {
name: name,
age: age,
energySource: energySource,
scare() {
console.log(catchPhrase);
}
}
};
const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'
팩토리 함수는 객체를 반환한다.
파라미터로 객체를 변경하여 반환할 수 있다.
const monsterFactory = (name, age) => {
return {
name: name,
age: age
}
}; //factory function
const monsterFactory = (name, age) => {
return {
name,
age
}
}; // property shorthand
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
// residence를 변수로 추출할때
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
// destructed assignment 를 이용하면 이런 식.
const { residence } = vampire;
console.log(residence); // Prints 'Transylvania'
//day를 변수로 추출할 때
const { day } = vampire.preferences;
console.log(day); // Prints 'stay inside'
객체의 key-value를 변수로 추출할 수 있다.
{} 를 이용해서 property를 변수로 추출한다.