-
Objects (2)JavaScript 2021. 10. 17. 11:40
이 글은 자바스크립트의 Objects(객체)에 관한 개념 및 문법을 정리하기 위해 작성하였습니다.< The this Keyword >
The this keyword refers to the calling object and which provides access to the calling object's properties.
(calling object : object that a method belongs to)
Method do not automatically have access to other internal properties of the calling object.ex)
// Not use this keyword const robot = { model: 'A-13', provideName() { console.log(model) } } robot.provideName(); // referenceError : model is not defined // Use this keyword const robot = { model: 'A-13', provideName() { console.log(this.model) } } robot.provideName(); // 'A-13'
< Arrow Functions and this >
Avoid using arrow functions when using this in a method.
- Arrow functios inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object.
ex)
const robot = { energyLevel: 100, checkEnergy: () => { console.log(`Energy is currently at ${this.energyLevel}%.`) } } robot.checkEnergy(); // Energy is currently at undefined%
reference :
https://developer.mozilla.org/en-US/docs/Glossary/Global_object,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
< Privacy >
If we don't want other code simply accessing and updating an object's properties.
- Use underscore( _ ) before the name of a property to mean that the property should not be altered.
(even so, it's possible to reassign '_property')
ex)
const object = { _property: 100 } object._property = 50; // it's possible to reassign '_property' but do not use it!
< Getters >
To get and return the internal properties of an object.
But they can do more than just retrieve the value of a property.
To respect the intention of properties prepended, or began, with underscore( _ )ex)
const robot = { _energyLevel: 100, get energyLevel() { if (typeof this._energyLevel === 'number') { return `my current energy level is ${this._energyLevel}`; } else { return 'system malfunction'; } } } // Call the getter method: robot.energyLevel; // my current energy level is 100 robot['energyLevel']; // my current energy level is 100
- Keep in Mind
1. Properties cannot share the same name as getter/setter function : _energyLevel ≠ energyLevel()
2. Getter methods do not use a set of parentheses ( ) : robot.energyLevel
Syntactically, it looks like we’re accessing a property.
< Setters >
To reassign private values of existing properties within an object.
To respect the intention of properties prepended, or began, with underscore( _ )ex)
const person = { _age: 37, set age(newAge){ if (typeof newAge === 'number'){ this._age = newAge; } else { console.log('You must assign a number to age'); } } }; // Call the setter method: person.age = 40; person['age'] = 40; console.log(person._age); // 40 person.age = '40'; // You must assign a number to age
- Keep in Mind
1. Properties cannot share the same name as getter/setter function : _age ≠ age(newAge)
2. Setter methods do not use a set of parentheses ( ) : person.age = 40
Syntactically, it looks like we’re accessing a property.
< Factory Functions >
To create many instances of an object quickly.
ex)
const robotFactory = (name, age, catchPhrase) => { return { name: name, age: age, score() { console.log(catchPhrase); } } } const ghost = robotFactory('Ghouly', '251', 'BOO!'); ghost.score(); // BOO!
< Property Value Shorthand >
For easier coding.
In case that the key name is same as the value name (parameter name)ex)
// Original const monsterFactory = (name, age) => { return { name: name, age: age } }; // Shorter Version const monsterFactory = (name, age) => { return { name, age } };
< Destructured Assignment >
To extract key-value pairs from objects and save them as variables in easier way.
- In destructured assignment, we create a variable with the name of an object’s key that is wrapped in
curly braces { } and assign to it the object.
ex)
const vampire = { name: 'Dracula', residence: 'Transylvania', preferences: { day: 'stay inside', night: 'satisfy appetite' } }; // Original const residence = vampire.residence; console.log(residence); // Transylvania // Shorter Version const { residence } = vampire; console.log(residence); // Transylvania const { day } = vampire.preferences; console.log(log); // stay inside
'JavaScript' 카테고리의 다른 글
Data type (0) 2021.10.25 Higher-Order Functions (0) 2021.10.19 Objects (1) (0) 2021.10.17 Loops (0) 2021.10.16 Arrays (0) 2021.10.14