const person = {
name : '홍길동',
age : 20
};
console.log(person.name);
const person = {
name : '홍길동',
age : 20
};
function print(p1){
const introduce = `제 이름은 ${p1.name}입니다.`;
console.log(introduce);
}
print(person);
const person = {
name : '홍길동',
age : 20
};
function print(p1){
const {name, age} = p1;
const introduce = `제 이름은 ${name}입니다.`;
console.log(introduce);
}
print(person);
객체에서 값들을 추출해서 새로운 상수로 선언해준다.
const person = {
name : '홍길동',
age : 20
};
function print({name,age}){
const introduce = `제 이름은 ${name}입니다.`;
console.log(introduce);
}
print(person);
const person = {
name : '홍길동',
age : 20,
hi: function hi(){
console.log('내 이름은 ' + this.name + ' 이야');
}
};
person.hi();
this는 객체인 자기 자신을 뜻한다.
주의할 점 : 함수를 function이 아닌 화살표 함수로 선언할 수 있지만 this가 들어가는 경우는 자기 자신을 참조할 수 없어 에러가 발생한다.
const numbers = {
_a: 1,
_b: 2,
sum: 3,
calculate() {
console.log('calculate');
this.sum = this._a + this._b;
},
get a() {
return this._a;
},
get b() {
return this._b;
},
set a(value) {
console.log('a가 바뀝니다.');
this._a = value;
this.calculate();
},
set b(value) {
console.log('b가 바뀝니다.');
this._b = value;
this.calculate();
}
};
console.log(numbers.sum); // 3 출력
numbers.a = 5; // _a를 5로 설정
numbers.b = 7; // _b를 7로 설정, sum 12로 설정
numbers.a = 9; // _a를 9로 설정, sum 16으로 설정
console.log(numbers.sum); // 16 출력