function 점수가져오기() {
return [100, 10, 50];
}
const 점수 = 점수가져오기();
// 개별 점수를 변수에 할당하기 ES5
const a = 점수[0],
b = 점수[1],
c = 점수[2]
// 개별 점수를 변수에 할당하기 ES6
const [a, b, c] = 점수가져오기();
console.log(a); // 100
console.log(b); // 10
console.log(c); // 50
const [x, y] = 점수가져오기();
console.log(x); // 100
console.log(y); // 10
...
스프레드 연산자 사용const [x, ...arg] = 점수가져오기();
console.log(x); // 100
console.log(arg); // [10, 50]
const [a, b, c, 세번째점수 = 90] = 점수가져오기();
// 4번째 배열 요소에 값이 있다면 90이 배열 아닌 요소의 값으로 할당된다.
console.log(세번째점수); // 4번째 배열이 없으니 기본 값인 90으로 할당 됨.
let a = 10,
b = 20;
[a, b] = [b, a];
console.log(a); // 20
console.log(b); // 10
const array = [90, 50, 10];
[array[0], array[2]] = [array[2], array[0]];
console.log(array); // [10, 50, 90];
const 내친구 = {
이름: "길동",
성: "홍"
};
// ES5 개체 속성을 변수에 할당하려는 경우
const 이름 = 내친구.이름;
const 성씨 = 내친구.성;
// ES6 개체 속성을 변수에 할당할 때
const { 이름: 친구이름, 성: 친구성씨 } = 내친구;
const { 객체속성 : 변수 } = 객체참조변수;
// 변수와 개체 속성의 이름이 동일한 경우
const { 이름, 성 } = 내친구;
const { 이름, 성, 나이 = 20 } = 내친구;
// 배열과 동일하게 객체 속성이 있는 경우 변수 기본 값은 무시된다.
const 홍길동 = {
나이: 25,
주소: {
지역: "경기도",
도시: "수원시"
}
};
const 길동이정보 = {
주소: {
지역,
도시
},
주소
};
console.log(지역); // "경기도"
console.log(도시); // "수원시"
console.log(주소); // { 지역: "경기도", 도시: "수원시" }
const 피자 = ({브랜드, 메뉴}) => console.log(`${이름}의 ${메뉴}가 맛있다.`);
const 피자가게 = {
브랜드 : "도미노피자",
메뉴 : "포테이토 피자"
};
피자(피자가게); // 도미노피자의 포테이토피자가 맛있다.
export
외부에서 선언 된 것을 불러올 땐 import
를 사용한다.import
명령 시 JS파일의 최상단에 입력하여 사용한다.// house.js
export const 우리집 = "경기도아파트";
// 먼저 정의하고 나중에 export를 하는 방법.
function 이사가기 () {
return "서울아파트";
};
export 이사가기;
-----------------------------------------------
// myInfo.js
import { 우리집, 이사가기 } from "./house.js";
console.log(우리집); // "경기도아파트"
const 새집 = 이사가기();
console.log(새집); // "서울아파트"
import
로 가져온 변수나 함수를 직접 변경할 수 없다.// house.js (단일 바인딩)
export 우리집 = "경기도아파트";
-----------------------------------------------
// myInfo.js
import { 우리집 } from "./house.js";
우리집 = "서울아파트"; // error
*
패턴을 사용한다. (네임스페이스 가져오기)// cal.js
export const a = 1,
b = 2;
export function sum() {
return a + b;
}
-----------------------------------------------
// main.js
import * as cal from "./cal.js";
const x = cal.a;
const y = cal.b;
const result = cal.sum(x,y);
-----------------------------------------------
// another.js
import { a } from "./cal.js";
import { b } from "./cal.js";
import { c } from "./cal.js";
/*
처음 import 이후 해당 모듈이 메모리에 로드되어 동일한 모듈을
참조하는 import 명령문이 있으면 메모리에서 재사용한다.
*/
// house.js
const 우리집 = "경기도아파트";
export { 우리집 as 집 };
-----------------------------------------------
// myInfo.js
import { 집 } from "./house.js";
console.log(집); // "경기도아파트"
----------------------------------------------
// another.js
import { 집 as 전에살던집 } from "./house.js";
console.log(전에살던집); // "경기도아파트"
default
를 통해 가져오는 방법을 좀 더 편하게 할 수 있다.{}
중괄호를 사용하지 않고 가져올 수 있다.// list.js
export default function(데이터) {
// 순서대로 리스트 내보내기
}
export function reverseList(데이터) {
// 역순으로 리스트 내보내기
}
----------------------------------------------
// main.js
import list, {reverseList} from "./list.js";
list(data);
reverseList(data);
// 기본 내보내기의 이름을 변경하려면
import { default as dataList, reverseList } from "./list.js";
=>
화살표를 이용하여 함수 표현식을 작성하기에 Arrow Function 이라고 한다.// 기본적인 함수 표현식
const sum = function (aNum, bNum) {
return aNum + bNum;
}
// 화살표 함수
// throw, return 과 같은 Statements 사용할 땐 {}로 감싸주어야함
const sum = (aNum, bNum) => {
return aNum + bNum;
}
// 표현식이 하나 일 경우 {}, return 생략 가능
const sum = (aNum, bNum) => aNum + bNum;
// 매개변수가 1개일 경우 () 생략 가능
const show = message => console.log(message);
// 매개변수가 없는 경우
const noParameter = () => console.log("noParameter");
()
소괄호로 감싸주어야 한다.()
로 묶어야함.const 색상설정 = 색상 => ({색: 색상});
const 바탕화면색상 = 색상설정("blue");
console.log(바탕화면색상.색); // blue
화살표 함수와 일반 함수
- 화살표 함수에서,
this
,arguments
,super
,new.target
은 어휘이다. 이는 화살표 함수가 둘러싸는 어휘 범위에서 이러한 변수(구문)을 사용한다는 의미- 화살표 함수는 생성자로 사용할 수 없다.
new
키워드를 사용하여 화살표 함수에서 새 개체를 만들면 오류가 발생한다.
this
의 값// 일반 함수의 경우
function Car() {
this.speed = 0;
this.speedUp = function (speed) {
this.speed = speed;
/*
selfThis와 같이 함수 내부에 변수를 선언하여 this를
할당해주어야 setTiemeOut에서 this가 이 변수를 가리킨다.
*/
const selfThis = this;
setTimeout(function () {
console.log(selfThis.speed); // 50
/*
selfThis 변수가 없다면 speedUp() 메서드 자체를 this로
가리키기에 정의되지 않은 undefined로 나온다.
*/
}, 1000);
};
}
let car = new Car();
car.speedUp(50);
-----------------------------------------------------
// 화살표 함수의 경우
function Car() {
this.speed = 0;
this.speedUp = function (speed) {
this.speed = speed;
setTimeout(
() => console.log(this.speed),
1000);
};
}
let car = new Car();
car.speedUp(50); // 50;
// ES6 이전 Class 문법
function Person (이름) {
this.이름 = 이름;
}
// Person.prototype 객체에서 getName 메서드 정의
Person.prototype.getName = function () {
return this.이름;
};
var jam = new Person("goodjam");
// 프로토타입 상속을 통해 jam = Person / Object의 인스턴스
console.log(jam.getName()); // "goodjam"
class
키워드를 사용한다.class
에서 constructor()
는 인스턴스의 속성을 초기화 할 수 있다.// ES6 문법
class Person {
constructor(이름) {
this.이름 = 이름;
}
// Person class의 메서드 getName()
getName() {
return this.이름;
}
}
const jam = new Person("goodjam");
const 내이름 = jam.getName();
Class 문법 정리
- 클래스 선언은 함수 선언과 같이 호이스팅되지 않는다.
- 클래스 선언 위치 위쪽으로 인스턴스를 선언하면
ReferenceError
- 클래스 내부의 코드는 엄격 모드에서 실행 된다. (변경 불가능)
- 클래스의 메서드는 열거 할 수 없다. (ex: for.. in)
- constructor/prototype pattern을 사용하는 경우 Object.defineProperty() 메서드를 사용하여 속성을 열거 불가능하게 해주어야 한다.
new
연산자 없이 클래스 생성자를 호출하면TypeError