영어는 잘 안 되지만 codecademy에서 바로바로 직접 코드를 쳐 가면서 개념 공부를 하니까 조금 더 빠르게 이해가 되는 것 같다.
오늘은 object에 대해서 공부를 했다. 인프런에서 자바스크립트 기초도 아예 안 된 상태에서 react강의를 들은 적이 있는데 이해가 거의 가지 않았다. javascript 객체에 대해서 무지한 상태여서 그런거 같다. 객체에 대해서 공부하면서 기초가 중요하다고 깨달았다.
let spaceship = {
'Fuel Type' : 'Turbo Fuel',
homePlanet : 'Earth',
color: 'silver',
'Secret Mission' : 'Discover life outside of Earth.'
};
// Write your code below
spaceship.color = 'glorious gold';
spaceship.numEngines = 5 ;
delete spaceship['Secret Mission'];
delete를 입력한 후 객체['키값']을 입력하면 객체의 속성이 사라진다.
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';
// Write your code below
let alienShip ={
retreat :function(){
console.log(retreatMessage);
},
takeOff : function(){
console.log('Spim... Borp... Glix... Blastoff!');
}
};
alienShip.retreat();
alienShip.takeOff();
ES6에 도입된 새로운 방법으로 콜론과 함수 키워드는 생략할 수 있게됐다.
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';
// Write your code below
let alienShip ={
retreat (){
console.log(retreatMessage);
},
takeOff (){
console.log('Spim... Borp... Glix... Blastoff!');
}
};
alienShip.retreat();
alienShip.takeOff();
var obj = {
x : 1,
y : true,
z : 'jaehee'
};
for (var k in obj) {
console.log(k + " : " + obj[k]);
}
/**
* --------------------------------
* 콘솔의 출력값
* --------------------------------
* x : 1
* y : true
* z : jaehee
* --------------------------------
*/
for in 문을 이용하여 객체의 프로퍼티명과 프로퍼티값을 열거하는 코드이다.
k는 obj의 key값을 출력하고 obj[k]는 obj의 value를 출력하는 걸 볼 수 있다.
참고로 for in 문은 배열도 객체로 놓고 보자면 인덱스의 숫자가 프로퍼티명에 해당하기 때문에 for in 문에 활용할 수 있다.
하지만 배열 요소를 나열할 때는 for in 문의 사용을 권장하지는 않는다고 한다.
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(dietType);
}
};
goat.diet();
// Output will be "ReferenceError: dietType is not defined"
이 코드에서 dietType이 정의되지 않았다고 나온다. goat객체 안에 dietType이라는 속성이 있는데도 정의 되지 않는다고 나온다. 하지만 diet()메서드의 scope가 {}안으로 정해져 있어서 나오지 않는것이다. dietType에 this를 넣어주면 이 문제가 해결이 된다.
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet();
// Output: herbivore
이 코드를 입력하면 정상적으로 출력이 되는 걸 볼 수 있다.