const text = `${hero.name}(${hero.actor}) 는 ${hero.weapon} 을 사용합니다.`;
비구조할당(객체구조분해)를 이용하면 좀 더 단순하게 작성이 가능.(아래 코드)
function print(hero) {
const { name, actor, weapon } = hero;
const text = `${name}(${actor}) 는 ${weapon} 을 사용합니다.`;
console.log(text);
}
더 나아가, 함수 파라미터를 안에서도 사용 가능.
function print({ name, actor, weapon }) {
const text = `${name}(${actor}) 는 ${weapon} 을 사용합니다.`;
console.log(text);
}
const { name } = ironMan;
console.log (name);
이렇게도 사용할 수 있다.
-객체안에 함수 넣기
const dog = {
name: '댕댕이',
sound: '멍멍',
say: function say(){
console.log(this.sound);
}
};
여기서 함수의 작성 형식은
say: function(){
console.log(this.sound);
이렇게도 가능하고
say(){
console.log(this.sound);
이렇게 해도 정상적으로 작동을 함.
반면에,
화살표 함수로
say:() => {
console.log(this.sound)
}
한다면 this가 뭔지 찾지 못함.
function으로 만든 함수는 this는 자기가 속해 있는 곳을 가르키지만
화살표 함수에서는 this를 자기가 어디 속해있는지 모름
함수에 있는 this는 자기가 속해있는 곳을 가르키게 되지만, 화살표 함수로 사용하게 되면, 화살표 함수 내부에서는 this가 어딘지 모름.
함수를 바깥으로 꺼내게 되면 꺼내는 순간 this와의 관계가 사라짐.
(아직 이해못함)
-객체 안에 GET 과 SET
const numbers ={
a: 1,
b: 2,
get sum() {
console.log('sum 함수 실행');
return this.a + this.b;
}
};
console.log(numbers.sum);
-GETTER 함수
sum이 함수인데도 마지막 줄에 console.log(numbers.sum());라고 하지않고 조회만 했는데도 함수는 실행이 됨.
이처럼 get함수는 특정값을 호출하지 않고 조회하려고 할 때 특정코드를 실행시키고 연산된 값을 받아서 사용하는 것을 의미한다.
getter 함수는 특정 값을 조회하려고 할 때 특정 코드를 실행시키고 연산된 값을 받아서 사용한다.
getter 함수는 파라미터 값을 가질 수 없다.
-SETTER 함수
setter 함수는 특정 값이 변경되어 질 때마다 함수를 실행하는데 사용한다.
setter 함수는 한개의 파라미터를 가져야 한다.
const dog = {
_name : '멍멍이',
get name (){
console.log('_name을 조회함');
return this._name;
},
//set함수를 쓸 때는 파라미터로 어떤 값을 무조건 설정해줘야함.
set name(value){
console.log('이름 체인지' + value);
this._name = value;
}
};
console.log(dog.name);
dog.name = '뭉뭉이';
console.log(dog.name);
/* 결과값
_name을 조회함
멍멍이
이름 체인지뭉뭉이
_name을 조회함
뭉뭉이 */
-(내피셜) 자바에서는 함수 호출 할 때 함수(); 이렇게 했었는데 자바 스크립트에서는 numbers.a = 5; 이면
컴파일러에서 자동으로 set을 호출한다(왜냐하면 이건 누가봐도 값 저장 이기 때문에.Get은 조회할 때 쓰고, Set은 값 설정할 때 쓰는거라 컴파일러가 알아서 판단하고 불러옴!)
***헷갈리지 말것! JS에서는 numbers.a < -- 이게 꼭 변수만을 뜻하는게 아님.
나는 처음에 numbers.a =5; 가 꼭 a라는 변수에 5를 대입하는 것 같아서 엄청 헷갈렸었다..
여기서의 numbers.a = 5는 set a(value)에서 5를 (value)라는 파라미터에 넘겨주는 것이다.
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){
this._a = value;
this.calculate();
},
set b(value){
this._b = value;
this.calculate();
}
};
console.log(numbers.sum);
numbers.a = 5;
numbers.b = 7;
console.log(numbers.sum);
-배열
객체는 한 변수 또는 상수 안에 여러가지 정보를 담기 위함 이었다면, 배열은 여러개의 항목들이 들어있는 리스트와 같은데 나열이 되어있음. JS의 배열에는 안의 모든 원소들이 다 똑같은 형태일 필요는 없다. 첫번째는 숫자, 두번째는 문자열, 세번째는 객체를 넣어도 상관X
#배열 내부함수
배열이름.length와 배열이름.push
const array = [1, "blah", {}, 4, 5];
console.log(array[0]);
const objects = [{ name: "멍멍이" }, { name: "야옹이" }];
console.log(objects[0]);
console.log(objects[1]);
// 배열에 새로운 항목 추가하기
//배열 내장함수인 push를 이용
console.log(objects.length);
objects.push({
name: "먕먕이"
});
console.log(objects[2]);
console.log(objects.length);
//console.log(objects.length);
//배열 안에 몇개가 있는지 알려줌.
#for문을 이용한 배열 출력
// for문과 배열
const names = ["멍멍이", "야옹이", "먕먕이"];
console.log(names.length);
// 배열의 인덱스는 항상 [0]부터 시작
for (let i = 0; i < names.length; i++){
console.log(names[i]);
}