객체 2 (ADVANCED OBJECTS)
1. this Keyword
어떠한 의미가 고정되어 있지 않고 그것을 사용하는 상황에 따라서 그 의미는 달라질 수 있다
가변적이다.
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
}
};
/* goat.makeSound(); // Prints baaa
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(dietType);
}
};
goat.diet();
// Output will be "ReferenceError: dietType is not defined"
why is dietType not defined even though it’s a property of goat?
That’s because inside the scope of the .diet() method,
we don’t automatically have access to other properties of the goat object.
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet();
// Output: herbivore
The this keyword references the calling object which provides access to the calling object’s properties. In the example above, the calling object is goat and by using this we’re accessing the goat object itself, and then the dietType property of goat by using property dot notation.
2. Arrow Functions and this
화살표 함수로서 this 를 불러올 수 없음
= short or long hand로 함수를 불러와야 함
const robot = {
energyLevel: 100,
checkEnergy: () => {
console.log(`Energy is currently at ${this.energyLevel}%.`)
}
}
robot.checkEnergy();
// Energy is currently at 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 energyLevel property and therefore returns undefined.
// shorthand
const robot = {
energyLevel: 100,
checkEnergy(){
console.log(`Energy is currently at ${this.energyLevel}%.`)
}
}
robot.checkEnergy(); //Energy is currently at 100%.
//long hand
const robot = {
energyLevel: 100,
checkEnergy : function(){
console.log(`Energy is currently at ${this.energyLevel}%.`)
}
}
robot.checkEnergy(); // 12345678
const robot = {
energyLevel: 100,
checkEnergy : function(){
console.log(`Energy is currently at ${this.energyLevel}%.`)
}
}
robot.checkEnergy(); //Energy is currently at 100%.
3. 접근제한자 (Private)
- 공개 여부를 결정하는 키워드
- 디자인 설계원칙(캡슐화, 정보은닉)과 관련
속성에 액세스하고 업데이트하는 것은 개체 작업에서 기본입니다. 그러나 다른 코드가 단순히 객체의 속성에 액세스하고 업데이트하는 것을 원하지 않는 경우가 있습니다. 객체의 프라이버시 를 논의 할 때 특정 속성 만 변경 가능하거나 가치를 변경할 수 있어야한다는 아이디어로 정의합니다.
특정 언어에는 객체에 대한 개인 정보 보호 기능이 내장되어 있지만 JavaScript에는이 기능이 없습니다. 오히려 JavaScript 개발자는 다른 개발자에게 속성과 상호 작용하는 방법을 알려주는 명명 규칙을 따릅니다. 일반적인 규칙 중 하나 _는 속성 이름 앞에 밑줄 을 두어 속성을 변경해서는 안된다는 의미입니다.
const robot = {
_energyLevel: 100,
recharge(){
this._energyLevel += 30;
console.log(`Recharged! Energy is currently at ${this._energyLevel}%.`)
}
};
robot._energyLevel= 'high';
robot.recharge(30); // Recharged! Energy is currently at high30%.
4. getter
Getter 는 객체의 내부 속성을 가져오고 반환하는 메서드
let test = 42
const robot = {
_model: '1E78V2',
_energyLevel: 100,
get energyLevel() {
if ( typeof this._energyLevel === typeof test) {
return `My current energy level is ${this._energyLevel}`;
} else {
return `System malfunction: cannot retrieve energy level`;
}
}
};
console.log(robot.energyLevel); //My current energy level is 100
5. setter
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
person._age = 'forty-five'
console.log(person._age); // Prints forty-five
6. Factory Functions
팩토리 함수는 객체를 반환하는 함수이며 여러 객체 인스턴스를 만들기 위해 재사용 할 수 있습니다.
팩토리 함수에는 반환되는 객체를 사용자 정의 할 수있는 매개 변수가있을 수도 있습니다.
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!'
7. Property Value Shorthand
const monsterFactory = (name, age) => {
return {
name: name,
age: age
}
};
const monsterFactory = (name, age) => {
return {
name,
age
}
};
8. Destructured Assignment
키 할당 을 줄이기 위해 비 구조적 할당 이라는 구조화 기술을 활용할 수도 있습니다 .
비 구조화 된 할당에서 중괄호로 싸인 객체 키 이름으로 변수를 생성하고 객체에 { }할당합니다
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
const { residence } = vampire;
console.log(residence); // Prints 'Transylvania'
const { day } = vampire.preferences;
console.log(day); // Prints 'stay inside'
9. Built-in Object Methods
예를 들어, 우리는 같은 객체 인스턴스 메서드에 액세스 할 수 있습니다 .hasOwnProperty(), .valueOf()그리고 더 많은! 설명서 읽기 기술을 연습하고 MDN의 객체 인스턴스 설명서를 확인하십시오 .
Object
The Object class represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.
developer.mozilla.org
이 같은 유용한 개체 클래스 메소드는 또한 Object.assign(), Object.entries()및 Object.keys()그냥 몇 이름을 지정합니다. 종합적인 목록을 보려면 MDN의 객체 인스턴스 문서를 찾아보십시오 .
Object
The Object class represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.
developer.mozilla.org
const robot = {
model: 'SAL-1000',
mobile: true,
sentient: false,
armor: 'Steel-plated',
energyLevel: 75
};
// What is missing in the following method call?
const robotKeys = Object.keys(robot);
console.log(robotKeys);
// Declare robotEntries below this line:
const robotEntries = Object.entries(robot);
console.log(robotEntries);
// Declare newRobot below this line:
const target = {laserBlaster: true, voiceRecognition: true};
const newRobot = Object.assign(target);
console.log(newRobot);