자바스크립트 지식이 부족한 것 같아 공부 해보았다.
객체
- 원시 타입(숫자, 문자열, 불리언, null, undefined 등) : 단 하나의 값만 나타낼 수 있고 불변
- 객체: 여러 가지 값이나 복잡한 값을 나타낼 수 있으며, 변할 수도 있다. 객체의 본질은 컨테이너이며 컨테이너의 내용물은 시간이 지나면서 바뀔 수도 있지만, 내용물이 바뀐다고 컨테이너가 바뀌는 건 아니다. 객체에는 중괄호를 사용하는 리터럴 문법을 사용한다.
- 객체의 콘텐츠는 프로퍼티(property) 또는 멤버(member)라고 부른다. 프로퍼티는 이름(Key)과 값(value)으로 구성. 프로퍼티 이름은 반드시 문자열 또는 심볼이어야 하며, 값은 어떤 타입이든 상관없고 다른 객체여도 상관없다.
객체는 멤버 접근 연산자인 . 과 계산된 멤버 접근 연산자인 [] 를 사용할 수 있다.
const obj = {};
obj.color = "yellow";
obj["The cake is a lie"] = 3;
obj["The cake is a lie"]; // 3
obj.color; // "yellow"
// 객체를 프로퍼티로 품을 수 있음
const sam = {
name: "Sam",
info: {
age: "20",
class: "Javascript",
},
};
// 모두 같은 결과로 '20'
sam.info.age;
sam.info["age"];
sam["info"].age;
sam["info"]["age"];
// 함수도 담을 수 있음
sam.etc = function () {
return "Bonk!";
};
sam.etc(); // "Bonk!"
// 삭제시 delete 연산자를 사용
delete sam.info;
delete sam.etc;
함수
기본적인 함수 지식
function getGreeting() {
return "Hello world!";
}
getGreeting(); // "Hello World!"
getGreeting; // function getGreeting()
// 변수에 할당
const f = getGreeting;
f(); // "Hello world!"
// 프로퍼티에 할당
const o = {};
o.f = getGreeting;
o.f(); // "Hello world!"
// 배열에 할당
const arr = [1, 2, 3];
arr[1] = getGreeting; // arr은 [1, function getGreeting(), 2]
arr[1](); // "Hello world!"
익명 함수 => 재귀 함수에선 함수 이름이 작성되어야 함.
const f = function () {
//...
};
화살표 표기법 (*)
- function 을 생략 가능
- 함수에 매개변수가 단 하나 뿐이라면 괄호도 생략 가능
- 함수 바디가 표현식 하나라면 중괄호와 return 문도 생략 가능
- 함수 이름이 없다
const f1 = function() {return "hello!";}
// 또는
const f1 = () => "hello!";
const f2 = function(name) {return `Hello, ${name}!`;}
// 또는
const f2 = name => `Hello, ${name}!`; //매개변수 있을 때
const f3 = function(a,b){return a+b;}
// 또는
const f3 = (a,b) => a+b;
//화살표 함수는 익명 함수를 만들어 다른 곳에 전달하려 할 때 가장 유용함
const o ={
name:'Julie',
greetBackWards: function(){
// const self = this; 사용하지 않아도 됨
const getReverseName = () => {
let nameBackwards = '';
for(let i=this.name.length-1; i>=0; i--){
nameBackwards += this.name[i];
}
return nameBackwards;
}
return `${getReverseName()} si eman ym, olleH`;
},
};
console.log(o.greetBackWards());
+ 화살표 함수에서 리턴 어떻게? >>
// 괄호 안에 이상한 문법이 들어가 버렸습니다...!
const newFunctionWrong = () => { a: '나는객체요소' };
// 소괄호로 감싸게 되면 객체 자체를 리턴할 수가 있게 됩니다.
const newFunction = () => ({ a: '나는객체요소' });
그 외 프로미스, async await, 제너레이터, 배열 등
map
- 일반적으로 for문 대신 사용 (파이썬에 비해 배열을 다루는 for문이 어렵고, map은 자체로 배열을 만들어 내는 메소드이기 때문에 매우 유용.)
- 배열.map(함수를 담습니다.) // 새로운 값을 가공할 함수 또는 로직
- 배열의 요소만큼 map에 작성된 함수가 수행됩니다. 인자는 두개를 받습니다.
- 1. 현재 요소의 값, 2. 현재 배열의 크기
// example
const a = [1, 2, 3, 4, 5];
const unit = a.map( (unit, idx) => {
return unit - 1;
} )
// unit: [0, 1, 2, 3, 4]
console.log(unit);
#1
const testObejct = {
a: '12345',
consoleA: function() {
console.log(this.a);
},
};
testObejct.consoleA(); //12345
위의 코드에서 this.a는 testObejct에서 a를 출력한다.
#2
const testObejct = {
a: '12345',
consoleA: function() {
console.log(this.a);
},
};
const globalConsoleA = testObejct.consoleA;
globalConsoleA(); // undefined
위의 코드에서 this.a는 globalConsoleA의 부모를 가리키는데, 아무 것도 없으니 글로벌을 가리킨다. 왜냐하면 globalConsoleA에 consoleA이 담겨지면서 그 메소드에서 가리키는 this가 원래의 부모 객체인 testObejct를 가리키지 않고 글로벌한 this를 가리키게 되는 것이다.
#3 해결 방안
const testObejct = {
a: '12345',
consoleA: function() {
console.log(this.a);
},
};
const globalConsoleA = testObejct.consoleA.bind(testObject);
globalConsoleA(); // 12345
위의 코드는 .bind()를 이용하여 this를 testObejct로 고정하는 방법을 사용하고 있다.
this가 testObejct를 가리키도록 하면 2번 코드의 문제를 해결 할 수 있다.
비구조화 할당 방법을 알면 useState 이해하기 쉽다.
함수형 컴포넌트에서 state 사용법.
const array = [10,20];
const one = array[0];
const two = array[1];
const array = [10,20];
const [one , two] = array;
import React, { useState } from 'react';
const Say = () => {
const [message , setMessage] = useState('');
const onClickEnter = () => setMessage('안녕하세요');
const onClickLeave = () => setMessage('안녕히 가세요!');
return (
<div>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
<h1>{message}</h1>
</div>
);
};
export default Say;
- 두 번째 인자인 setMessage는 message에 대한 setter함수이다. (message를 setting)
- message를 변경 시킬 수 있는..
- 디폴트를 ' '로!