const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(dietType);
}
};
goat.diet();
// Output will be "ReferenceError: dietType is not defined"
Why? 왜 goat 객체는 diet 매소드를 인보킹 했을때 dietType을 접근할수 없을까. - That’s because inside the scope of the .diet() method, we don’t automatically have access to other properties of the goat object. 객체 안에서의 매소드는 같은 객체의 프로퍼티 dietType을 리퍼런스를 할수 없다 허나, this.를 쓴다면 가능
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet(); // herbivore
객체안의 this 키워드는 그 객체의 프로퍼티를 접근 할수있게 한다.
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.
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet: () => {
console.log(this.dietType);
}
};
goat.diet(); // Prints undefined
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
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.
애로우 함수에 this 는 항상 자신을 둘러싸고 있는 상위 환경의 this 그대로 계승하는 Lexical this를 따른다.
const Foo = () => { console.log(this); }
const foo = new Foo(); // TypeError: Foo is not a constructor
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
const person = { name: 'Lee', };
Object.prototype.sayHi = () => console.log(`Hi ${this.name}`);
person.sayHi(); // Hi undefined
//출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
const box = document.getElementById('box');
box.addEventListener('click', () => { console.log(this); //window });
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
이미지 출처: Dmtri Pavlutin
When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value.
Certain languages have privacy built-in for objects, but JavaScript does not have this feature. Rather, JavaScript developers follow naming conventions that signal to other developers how to interact with a property. One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered.
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'
Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. If we do so, then calling the method will result in an infinite call stack error. One workaround is to add an underscore before the property name like we did in the example above.
Along with getter methods, we can also create setter methods which reassign values of existing properties within an object.
const person = {
_age: 37,
set age(newAge){
if (typeof newAge === 'number'){
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
Nonetheless, even with a setter method, it is still possible to directly 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
There are times where we want to create many instances of an object quickly. Here’s where factory functions come in.
A factory function is a function that returns an object and can be reused to make multiple object instances.
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 dailyMenuSystem = {
dish: '햄버거',
price: 0,
}
ES6 introduced some new shortcuts for assigning properties to variables known as destructuring.
In the previous exercise, we created a factory function that helped us create objects. We had to assign each property a key and value even though the key name was the same as the parameter name we assigned to it.
const monsterFactory = (name, age) => {
return {
name,
age
}
};
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
// Too much keystrokes
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
// basic destructured assignment
const { residence } = vampire;
console.log(residence); // Prints 'Transylvania'
// Renaming variables when destructring obj
const {residence: address} = vampire;
Useful Refs:
getters/setters === access property by javascript.info