SlideShare uma empresa Scribd logo
1 de 97
1
Copyright blog.xcoda.net
ES5 & ES6
Rev. JS303
이세우
(dltpdn@gmail.com, blog.xcoda.net)
기업 및 영리를 목적으로 하는 교육에 허락 없이 사용할 수 없습니다.
2
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
3
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 정의
 Object.defineProperty(obj, prop, desc), defineProperties(obj, props)
 Data Descriptor
 value : 속성 값(*undefined)
 writable : {true|*false}, 쓰기(값의 할당)금지 여부
 enumerable : {true|*false}, for-in문, keys() 출력 여부
 configurable :{true|*false}, 제거 및 설정변경 여부
 Access Descriptor
 set : {function | *undefined}, 인자의 값이 속성의 값
 get : {function | *undefined} , 함수의 반환값이 속성의 값
 Data descript와 Access Descriptor 는 동시에 정의 불가
 Object.getOwnPropertyDescriptor(obj, prop)
4
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 정의
 Data Descriptor
var obj = {};
Object.defineProperty(obj, 'name', {
value :'lee'
writable : false,
enumerable : false
});
obj.name; // 'lee'
obj.name = 'kim'; // no effect or error in strict mode
delete obj.name; // false
for(var key in obj){ //no loop execution
console.log(key);
}
Object.getOwnPropertyDescriptor(obj, 'name');
5
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 정의
 Access Descriptor
function Person(name, age){
var _name =name;
var _age = age;
Object.defineProperty(this, 'name', {
get: function(){
console.log('get name');
return _name;
},
set : function(name){
console.log('set name');
_name = name;
}
});
Object.defineProperty(this, 'age', {
set : function(age){
console.log('set age');
_age = age;
},
get : function(){
console.log('get age');
return _age;
}
});
};
Person lee = new Person('lee', 27);
lee.name = 'kim';
lee.age = 23;
console.log(lee.name); // 'kim'
console.log(lee.age); // 23
6
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 정의
 Getter/Setter Accessor
 { get prop(){...} }
var value = 0;
var obj = {
get v(){
console.log('getter.');
return value;
},
set v(v){
console.log('setter:'+v);
value = v;
}
};
obj.v = 10; // setter:10
console.log(obj.v); // gettter. 10
7
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 descriptor 변경
 정의된 속성의 writable/configurable/enumarable 변경
 configurable = false 인경우 Error
var obj = {};
Object.defineProperty(obj, 'name', {
value :'lee'
writable : true
});
var desc = Object.getOwnPropertyDescriptor(obj, 'name');
desc.writable = false;
Object.defineProperty(obj, 'name', desc);
8
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 정의
 Object.defineProperties(obj, props) : 여러 속성을 한번에 정의
var obj = {};
Object.defineProperties(obj, {'name', {
value :'lee',
writable : false,
enumerable : false
},
'age', {
value : 27,
writeable : true,
enumerable : true
}
}
);
9
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 확장 제어
 Property 동적 추가 불가
 Object.preventExtensions( obj )
 Object.isExtensionsible( obj)
var obj = {};
Object.preventExtensions(obj);
Object.isExtensionsible(obj); // true
obj.name = 'lee'; // 효력 없음, Error in strict mode
Object.defineProperty(obj, 'name', {
value :'lee'
writable : false,
enumerable : false
}); // Error
10
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 봉인
 Object.seal(obj)
 Object.isSeal(obj)
 모든 속성의 descriptor의 변경 불가
 preventExtensions() + 모든 속성에 대해서 configurable = false
 구현 사례
Object.seal = function( obj ) {
var props = Object.getOwnPropertyNames( obj );
for ( var i = 0; i < props.length; i++ ) {
var desc = Object.getOwnPropertyDescriptor( obj, props[i] );
desc.configurable = false;
Object.defineProperty( obj, props[i], desc );
}
return Object.preventExtensions( obj );
};
11
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 Freezing
 Object.freeze(obj)
 Object.isFrozen(obj)
 객체 속성의 확장, writable, configurable 불가
 Seail + (writable = false)
 구현 사례
Object.freeze = function( obj ) {
var props = Object.getOwnPropertyNames( obj );
for ( var i = 0; i < props.length; i++ ) {
var desc = Object.getOwnPropertyDescriptor( obj, props[i] );
if ( "value" in desc ) {
desc.writable = false;
}
desc.configurable = false;
Object.defineProperty( obj, props[i], desc );
}
return Object.preventExtensions( obj );
};
12
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 생성 및 상속
 Object.create( parent, propDesc )
 지정한 객체를 상속받는 객체 생성
 property descriptor를 지정
function Person(name, age){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
var parent = new Person('lee');
var child = Object.create(parent, {'age': {
value :27
}
});
child.getName(); // 'lee'
child.age; // 27
13
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 생성 및 상속
 Object.create( parent, propDesc )
 구현 사례
Object.create = function( proto, props ) {
var ctor = function( ps ) {
if ( ps )
Object.defineProperties( this, ps );
};
ctor.prototype = proto;
return new ctor( props );
};
14
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 속성 조사
 Object.keys( obj ) :
 enumarable 속성을 배열로 반환
 Object.getOwnPropertyNames( obj ) :
 직접 소유한 속성을 배열로 반환
 Object.getOwnPropertyDescriptor( obj , 'prop name') :
 지정한 속성에 대한 descriptor를 반환
var obj = {name: 'lee', age : 27};
Object.defineProperty(obj, 'addr', {
value:'seoul', enumarable:false
});
Object.keys(obj); // [name, age]
Object.getOwnPropertyNames(obj); //[name, age, addr]
15
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Object
 객체 관련 기타 사항
 마지막 콤마(,) 허용
 JSON 객체의 마지막 속성
 배열 요소의 마지막 요소
 예약어(key word)를 속성으로 사용 가능
var obj = {name: 'lee', age : 27, };
var array = [1,2,3,4,5,]
obj.if = 'interface';
obj.var = 4
16
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array 기능 확대
 Array.isArray()
 .indexOf(seachElement [, fromIndex=0]), lastIndexOf()
 .forEach()
 .every(callback [, thisArg]);
 .some()
 .filter()
 .map()
 .reduce()
 .reduceRight()
17
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 Array.isArray()
 배열 여부 확인
Array.isArray([]); //true
Array.isArray([1]); //true
Array.isArray(new Array()); //true
Array.isArray({}); // false
Array.isArray(10); //false
Array.isArray(); //false
Array.isArray(undefined); // false
18
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .indexOf(seachElement [, fromIndex=0])
 .lastIndexOf(seachElement [, fromIndex=0])
 배열 요소 검색
 반환 : not found : -1
 fromIndex
 검색을 시작할 index
 음수인 경우 배열 끝에서 부터 offset, 검색은 앞에서 뒤로
 (역방향 검색 아님)
var array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
19
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .forEach(callback [, thisArg]);
 callback(currentElement, index, array)
 배열의 모든 요소에 대해서 callback 함수 호출
 초기화 되지 않거나 삭제된 요소에 대해서는 호출 생략
[3,2,9,1].forEach(function(el, idx, array){
console.log(idx +":" + el);
});
//0:3
//1:2
//2:9
//4:1
20
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .every(callback [, thisArg]);
 callback(currentElement, index, array)
 배열의 모든 요소가 callback함수의 조건을 만족하는지 확인
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
21
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .some(callback [, thisArg]);
 callback(currentElement, index, array)
 배열의 모든 요소 중 하나라도 callback함수의 조건을 만족하는지 확인
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
var fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
return arr.some(function(arrVal) {
return val === arrVal;
});
}
checkAvailability(fruits, 'kela'); //false
checkAvailability(fruits, 'banana'); //true
22
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .filter(callback [, thisArg]);
 callback(currentElement, index, array)
 callback함수의 조건을 만족하는 요소들로 구성된 새로운 배열 생성
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
23
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .map(callback [, thisArg]);
 callback(currentElement, index, array)
 배열의 모든 요소에 대해서 callback함수의 결과 값을 갖는 새로운 배열 생성
[1, 2, 3].map(function(el, idx, array){
return el * el;
});
//[ 1, 4, 9 ]
['1', '2', '3'].map(function(el, idx, array){
return parseInt(el, 10);
}); // [1, 2, 3]
['1', '2', '3'].map(Number); //[1,2,3]
24
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .reduce (callback [, initialValue]);
 callback(preElement, currentElement, index, array)
 index 1에서 부터 실행
 pre : 최초 실행시 0번째 요소, 이후는 이전 callback의 반환값
[0, 1, 2, 3, 4].reduce(function(pre, curr, idx, array) {
return pre + curr;
}); // 10
호출횟수 pre curr idx return
1 0 1 1 1
2 1 2 2 3
3 3 3 3 6
4 6 4 4 10
25
Copyright blog.xcoda.net
3.ES5 & ES6ES5 Array
 Array
 .reduceRight(callback [, initialValue]);
 callback(preElement, currentElement, index, array)
 reduce 호출을 배열 요소의 오른쪽에서 부터
[0, 1, 2, 3, 4].reduce(function(pre, curr, idx, array) {
return pre + curr;
}); // 10
호출횟수 pre curr idx return
1 4 3 3 7
2 7 2 2 9
3 9 1 1 10
4 10 0 0 10
26
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
27
Copyright blog.xcoda.net
3.ES5 & ES6ES5 String
 String
 .trim()
 앞뒤 공백(space, tab, 줄바꿈 기호) 제거
 프로퍼트 접근
 인덱스를 프로퍼티 이름으로 접근
var str = ' abc ';
console.log(str.trim()); // 'abc'
var str2 = 'abc';
str2[2]; // 'c'
28
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
29
Copyright blog.xcoda.net
3.ES5 & ES6ES5 기타
 Function
 .bind(thisArg [ , arg1, arg2...]);
 함수 호출에 사용할 this 객체를 지정하여 새로운 함수 반환
 call()/applay()는 호출할 때 마다 지정
var obj = {name: 'lee'};
function f(){
return this.name;
}
f(); // undefined
var obj_f = f.bind(obj);
obj_f(); // 'lee'
30
Copyright blog.xcoda.net
3.ES5 & ES6ES5 기타
 Date
 new Date( ISOString),
 .toISOString()
 .now()
 JSON
 JSON.parse()
 JSON.stringify()
31
Copyright blog.xcoda.net
3.ES5 & ES6ES5 기타
 Strict Mode
 ECMAScript 3 기능 중 Deprecated 된 것을 사용할 수 없게 한다.
 정의되지 않은 변수에 할당 불가
 객체 Property의 변경 불가(아래의 경우)
 writable=false , 수정 불가
 configurable= false, 삭제 불가
 extensible=false, 추가 불가
 Eval
 eval을 ID로 사용 불가
 eval() 함수 내에서 변수 선언 불가
 Function
 arguments 객체에 할당 불가
 arguments.callee 사용 불가
 arguments.caller 사용 불가
 with(){} 구문 사용 불가
<script type="text/javascript>
"use strict"
...
//or
function imStrict(){
"use strict"
// code here....
}
32
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
33
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 변수 선언
 let
 block scope 변수 선언
 재정의 불가
 var은 funciton scope 변수 선언
var a = 1;
var a = 10; // OK
console.log(a); // 10
let b = 1;
let b = 10; // Error
function f(){
var x = 10;
let y = 20;
}
console.log(x); // 10
console.log(y); // Error, not defined
34
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 변수 선언
 const
 상수 선언
 값의 재할당 금지
 let 과 동일한 scope 정책
 객체 참조의 경우 객체 자체는 가변(C 언어와 차이)
const V = 10;
V = 20; // Error
const OBJ = { name : 'lee'};
OBJ.name = 'kim'; // OK
OBJ = {name:'kim'}; // Error
35
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Default Parameter
 함수의 매개변수에 기본 값 지정
 undefined 값의 전달 기본 값 적용
 old style
 ES6 style
function f(x, y, z){
x = x || 1;
y = y || 2;
z = z || 3;
console.log(x, y, z);
}
f(10, 20); // 10, 20, 3
function f(x = 1, y = 2, z = 3){
console.log(x, y, z);
}
f(10, 20); // 10, 20, 3
36
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Spread Operator(펼침 연산자) : ...arg
 배열과 같은 Iterable 객체의 요소
 함수에 전달 할때 개별 항으로 취급
 old style
 ES6 style
function f(a, b){
return a + b;
}
var array = [2, 3];
f(array[0], array[1]); // 5
f.apply(null, array);//5
function f(a, b){
return a + b;
}
var array = [2, 3];
f(...array);//5
37
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Spread Operator(펼침 연산자) : ...arg
 부분 배열
 배열 합치기
let array1 = [1,2,3];
let array2 = [0, ...array1, 4,5,6,] // [0, 1,2,3,4,5,6]
let array1 = [1,2,3];
let array2 = [4,5];
array1.push(...array2); // [1,2,3,4,5]
38
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Rest Operator(나머지 연산자) : ...arg
 함수 선언부의 마지막 파라미터에 "..." 작성
 지정된 파리미터 이외의 값을 배열형식으로 전달
function f(a, b, ...args){
console.log(args);
}
f(1,2,3,4,5); //[3,4,5]
39
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Destructuring Assignment(해체 할당)
 Iterable/Object 각각의 요소/속성을 여러 변수에 한번에 할당
 배열 해체 할당
var array = [1,2,3];
var a = array[0];
var b = array[1];
var c = array[2];
var x,y,z;
[x,y,z] = array;// x:1, y:2, z :3
var [aa, bb, cc] = array;// aa:1, bb:2, cc:3
40
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Destructuring Assignment(해체 할당)
 값 건너 뛰기
 나머지 연산자
 기본값 할당
 파라미터로 해체 할당
let [a, , b] = [1,2,3]; // a:1, b:3
let [a, ...b] = [1,2,3,4,5]; //a:1, b:[2,3,4,5]
let [a, b, c = 3] = [1,2]; // a:1, b:2, c:3
function f([a,b,c=3] = [1,2,3]){ ... };
f(undefined);
41
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Destructuring Assignment(해체 할당)
 객체 해체 할당
 객체 프로퍼티를 각각의 개별 변수에 할당
 프로퍼티와 변수의 이름을 갖게
var obj = {name:'lee', age:27};
var name, age;
({name, age} = obj);
console.log(name, age); // 'lee', 27
var a, b;
({name:a, age:b} = obj);
console.log(a, b); // 'lee', 27
var {name:x, age:y} = obj;
console.log(x, y); //'lee', 27
42
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Arrow Function
 람다 식, 익명 함수
 (parameter)=>{ ... body...}
 함수 body의 문이 한줄 이면 return 과 {} 생략 가능
 파라미터가 1개 이면 () 생략 가능
 파라미터 없으면 () 생략 불가
(param1, param2, ..., paramN) => { statements }
(param1, param2, ..., paramN) => expression
(singleParam) => { statements }
singleparam => { statements }
() => { statements }
var plus = (a,b)=>{ return a+b};
plus(1, 2); //3
var plus = (a, b)=> a+b;
plus(3, 4); // 7
43
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Arrow Function
 Lexical this
 일반 함수와 같이 this 사용 불가
 바깥 함수의 this를 사용
var obj = { name: 'lee', getName: function(){ return this.name;}};
obj.getName(); // 'lee'
var obj2 = {name: 'lee', getName: ()=>this.name};
obj2.getName(); //undefined
var obj3 = {name:'lee', getName:function(){
return (()=>this.name)();
}}
obj3.getName(); // 'lee'
44
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Arrow Function
 Lexical this
 일반 함수와 같이 this 사용 불가
 바깥 함수의 this를 사용
 생성자 사용 불가(new 사용 불가)
var obj = { name: 'lee', getName: function(){ return this.name;}};
obj.getName(); // 'lee'
var obj2 = {name: 'lee', getName: ()=>this.name};
obj2.getName(); //undefined
var obj3 = {name:'lee', getName:function(){
return (()=>this.name)();
}}
obj3.getName(); // 'lee'
var arrow = () => 'hello';
new arrow(); // Error
45
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Syntax
 Object literal
 편리한 프로퍼티 값 할당
 편리한 메서드 정의
 computed property name(조합 프로퍼티명)
var name = 'lee', age = 27;
var obj = {name, age};
var obj = {
hello(){
console.log('hello world');
}
};
obj.hello(); // 'hello world'
var obj = { ['last' + 'name'] : 'lee'};
obj.lastname; // 'lee';
obj['last' + 'name']; //'lee'
46
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
47
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Number
 2진수 리터럴 :
 0b
 8진수 리터럴
 ES5 :0
 ES6 : 0o
 isInteger() :
 정수 판별
let bi = 0b00001111;
console.log( bi === 15, bi); // true 15
let oct = 010; // 8
let oct2 = 0o10; // 8
Number.isInteger(123);//true
Number.isInteger(3.14);//false
Number.isInteger("123");//false
Number.isInteger("abc");//false
48
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Number
 isNaN() :
 NaN 판별 : 오직 NaN만 true
 global.isNaN() : 숫자로 변환할 수 없으면 모두 true
 isFinite() :
 유한숫자 판별 : 오직 숫자만 true
 global.isFinite() : 숫자로 변환 할 수 있으면 true
isNaN(123);// false
isNaN('123');// false
isNaN('abc'); //true
isNaN(NaN); // true
Number.isNaN(123);// false
Number.isNaN('123');//false
Number.isNaN('abc');//false
Number.isNaN(NaN); // true
isFinite(10); //true
isFinite(null); //true
isFinite('');//true
isFinite(1/0); //false
Number.isFinite(10);//true
Number.isFinite(null); // false
Number.isFinite(''); // false
Number.isFinite(1/0); // false
49
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Number
 Number.EPSILON
 약 2-52
 부동 소수점의 미세한 오차 무시하는데 사용
console.log(0.1 + 0.2);// 0.30000000000000004
console.log(0.1 + 0.2 == 0.3);// false
function epsilonEqual(a, b){
return Math.abs(a-b) < Number.EPSILON;
}
console.log(epsilonEqual(0.1+0.2, 0.3));//true
50
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Math
 삼각 연산
 하이퍼 볼릭
 Math.sinh(), Math.cosh(), Math.tanh(),
 역 하이퍼 볼릭
 Math.asinh(), Math.acosh(), Math.atanh()
 피타고라스 정리
 Math.hypot()
 산술 연산
 Math.log2(), Math.log10(), Math.log1p(), Math.expm1(), math.cbrt()
 32비트
 Math.imul(), Math.clz32()
 기타
 Math.sign() : 양수 음수 구분, 1, 0, -1로 반환
 Math.trunc() : 가수부 덜어낸 정수부 반환
 Math.fround() : 32비트 부동 소수점 값으로 반올림
51
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 String
 .repeat(times) : 지정한 횟수 만큼 연결
 includes(string[, index]) : 지정한 문자열 포함 여부
 startsWith(str[, index]), endsWith(str[, index])
console.log('z'.repeat(6));//zzzzzz
var s = 'hello world';
s.includes('hello'); //true
var s = 'hello world';
s.includes('hello'); //true
52
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 String
 template 문자열
 역 따옴표(`)
 place holder : ${}
 multi line string
 tagged template
var name = 'Lee', age = 27;
var template = `Hello! my name is ${name}, ${age} years old`;
console.log(template);// 'Hello! my name is Lee, 27 years old'
function tag(strings, ...values){
console.log(strings);
console.log(values);
return strings[0] + strings[1] + (values[0] + values[1]);
}
var a=10, b=20;
var temp = tag `hello ${a} world ${b}`; // 'hello world 30'
53
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Array
 Array.from(iterable [, callback[, thisArg]])
 callback(value, idx)
 배열 비슷한 객체를 배열로 생성
 iterable
 length 속성을 갖음
 index로 요소 접근
Array.from([1, 2, 3], x => x + x); // [2, 4, 6]
Array.from({length:5}, (val, idx)=>{
console.log(val, idx);
return idx
});
undefined 0
undefined 1
undefined 2
undefined 3
undefined 4
[ 0, 1, 2, 3, 4 ]
54
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Array
 Array.of(element0 [, element n]);
 주어진 요소로 배열 생성
 new Array()와 차이
 .fill(value [, start=0 [, end = length]])
 지정된 값으로 배열을 채운다.
new Array(5); //[ ,,,,], length:5
Array.of(5); // [5], length:1
Array.of(1,2,3); //[1,2,3], length:3
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
55
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Array
 .find(callback, thisArg)
 callback을 만족하는 요소 반환
 callback(value, index, array)
 .findIndex(callback, thisArg)
 find와 동일, 값이 아닌 index 반환
var people = [
{name:'lee', age:27},
{name:'kim', age:23},
{name:'park', age:30}
];
people.find(function(val, idx, arr){
return val.name = 'kim';
}); //{ name: 'kim', age: 27 }
56
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Array
 .copyWithin(target, start[, end = this.length)
 배열 내 요소를 다른 위치에 복사
 entries(), keys(), values()
 배열을 iterable 객체로 반환
[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]
var entries = [1,2,3].entries();
console.log(...entries); //[0, 1] [1, 2] [2, 3]
var keys = [1,2,3].keys(); // 0 1 2
console.log(...keys);
var values = [1,2,3].values();
console.log(values); // 1 2 3
57
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 ArrayBuffer
 new ArrayBuffer(length) , length : byte
 고정 길이 binary data
 1Byte 데이타 블록 하나가 원소
 Typed Array 또는 DataView를 이용
 DataView(buffer [, byteOffset [, byteLength]])
 ArrayBuffer에 숫자를 읽고 쓰기 위한 인터페이스
 setXXX(offset, value, bigEndian), getXXX(offset, bigEndian);
 set/getInt8, set/getUint8, set/getInt16, set/getUint16
 set/getInt32, set/getUint32, set/getFloat32, set/getFloat64
let buff = new ArrayBuffer(80);
let view = DataView(buff);
view.setInt32(8, 22, false);
var number = view.getInt32(8, false);
console.log(number);//22
58
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Typed Array
 DataView의 offset 계산을 편리하게 위한 wrapper
 Int8Array, Uint8Array, Int16Array, Uint16Array
 Int32Array, Uint32Array, Float32Array, Float64Array
 new XXArray(buffer [, byteOffset [, length]])
 new XXArray(length)
 new XXArray(array)
let buff = new ArrayBuffer(80);
let typed = new Int32Array(buff);
typed[0] = 22;
console.log(typed.length, typed[0]); // 20 22
let int16 = new Int16Array(2);
int16[0] = 10;
int16[1] = 20;
console.log(int16); // {0=10, 1=20}
let x = new Int16Array([21, 31]);
console.log(x); // {0=21, 1=31}
59
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Set
 new Set([iterable])
 값의 중복을 허용하지 않는 컬렉션
var myset = new Set();
myset.add(1);
myset.add(5);
myset.add('hello');
var obj = {name:'lee'};
myset.add(obj);
myset.has(1); // true
myset.has(3); // false
myset.has(5); // true
myset.has("hello"); //true
myset.size; //4
myset.delete(5); // true
myset.has(5); // false
myset.size; //3
60
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Map
 new Map([iterable])
 key : value 쌍으로 저장
let map = new Map();
map.set("name", 'lee');
map.set("age", 27);
map.size; // 2
for (var [key, value] of map) {
console.log(key + " = " + value);
}
map.has("name"); // true
map.get("age"); // 27
map.delete("age"); //true
map.size; //1
map.clear();
61
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 WeakSet
 Object 만 저장 가능
 weekly held object reference
 저장된 객체에 대한 다른 참조가 없으면 garbage collection
 WeakMap
 Object 만 저장 가능
 weekly held object reference
 저장된 객체에 대한 다른 참조가 없으면 garbage collection
62
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Built-in APIs
 Object
 Object.is(value1, value2)
 두 값의 동등 여부 판단
 === 과 차이
 Object.assign(target, ...sources)
 source의 프로퍼티를 target에 복사
0 === -0; // true
Object.is(0, -0); //false
NaN === NaN; //false
Object.is(NaN, NaN); //true
NaN === 0/0; //false
Object.is(NaN, 0/0); true
var obj = {name:'lee'};
var obj2 = {age : 27};
Object.assign(obj, obj2);
obj.name; // 'lee'
obj.age; // 27
63
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
64
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Iterator
 Symbol
 Symbol([descriptor])
 유일한 값 생성
 ES6에서 추가된 primitive type
 객체의 property key로 사용
 new 키워드 사용 불가
 Object.getOwnPropertySymbols()
 getOwnPropertyNames()에 대응하는 함수
var sym1 = Symbol();
var sym2 = Symbol();
sym1 === sym2; //false
var obj = {[sym1] : 1};
obj[sym1];// 1
Object.getOwnPropertySymbos(obj);// Symbol()
65
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Iterator
 Symbol
 Symbol.for("key")
 "key"에 해당하는 Symbol을 생성하거나 반환한다.
 전역 영역의 registry, Symbol()의 scope 문제 해결
 Well-known symbol
 이미 만들어 놓은 symbol
 Symbol.iterator
 Symbol.match
let obj = {};
(function(){
let s1 = Symbol();
obj[s1] = 'lee';
})();
obj[s1];// Error
let obj = {};
(function(){
let s1 = Symbol.for("name");
obj[s1] = 'lee';
})();
obj[Symbol.for("name")]; // 'lee'
66
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Iterator
 Iterator protocol
 next 함수 제공
 value, done 프러퍼티를 갖는 객체 반환
 value : 다음 값, done: 순회 끝 여부
 Iterable protocol
 Symbol.iterator를 키로 하는 Iterator protocol을 만족하는 함수 구현
 @@iterator
let obj = {
array: [ 1,2,3,4],
nextIndex : 0,
[Symbol.iterator] : function(){
return {
array: this.array,
next: function(){
return this.nextIndex < this.array.length ?
{value : this.array[this.nextIndex++], done:false}:
{done:true};
}
}
}
}
67
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Iterator
 Generator
 function*
 재 진입 가능 함수
 매 next()마다 다음 yield 지점까지만 실행
function* idMaker(){
var index = 0;
while(index < 3)
yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
68
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Iterator
 for ... of loop
 for( variable of iterable)
 next()호출을 자동으로 진행
let iterable = [1, 2, 3];
for (let value of iterable) {
console.log(value);
}
// 1
// 2
// 3
69
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
70
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise
 new Promise(function(resolve, reject){ ... })
 excutor
 이행하면 resolve, 거절하면 reject
 인스턴스 상태
 pending : 초기상태
 fulfilled : 성공
 rejected : 실패
 settled : 종료
 then(onFullfilled, onRejected)
 catch(), all()
71
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise
 then()
var doAsync = function(condition){
return new Promise(function(resolve, reject){
setTimeout(function(){
if(condition){
resolve("success");
}else{
reject("fail");
}
}, 3000);
}
};
doAsync(true).then(function(value){
console.log('ok:' + value);
}, function(reason){
console.log('fail:' + reason);
});
72
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise
 then(), catch()
var doAsync = function(condition){
return new Promise(function(resolve, reject){
setTimeout(function(){
if(condition){
resolve("success");
}else{
reject("fail");
}
}, 3000);
}
};
doAsync(true).then(function(value){
console.log('ok:' + value);
}).catch(function(reason){
console.log('fail:' + reason);
});
73
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise
 chainning
 No return : 새로운 fulfilled Promise 객체 생성 연결
 return new Promise : new Promise 객체 연결
 return value : new Promise 객체 연결
asyncThing1()
.then(function() { return asyncThing2();})
.then(function() { return asyncThing3();})
.catch(function(err) { return asyncRecovery1();})
.then(function() { return asyncThing4();}, function(err)
{ return asyncRecovery2(); })
.catch(function(err) { console.log("Don't worry about it");})
.then(function() { console.log("All done!");});
74
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise.all()
 모든 비동기 작업이 끝나면
var promise1 = new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("첫번째 Promise 완료");
resolve("11111");
}, Math.random() * 20000 + 1000);
});
var promise2 = new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("두번째 Promise 완료");
resolve("222222");
}, Math.random() * 10000 + 1000);
});
Promise.all([promise1, promise2]).then(function (values) {
console.log("모두 완료됨", values);
});
75
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Promise
 Promise.race()
 모든 비동기 작업 중 하나라도 완료되면
var promise1 = new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("첫번째 Promise 완료");
resolve("11111");
}, Math.random() * 20000 + 1000);
});
var promise2 = new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("두번째 Promise 완료");
resolve("222222");
}, Math.random() * 10000 + 1000);
});
Promise.race([promise1, promise2]).then(function (values) {
console.log("하나 완료됨", values);
});
76
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
77
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect
 동적인 객체와 함수에 대한 조작
 Object API와 중복되는 것을 보완 및 정리한 API
 new 연산자 사용 불가
 함수 호출 불가
 Reflect.apply()
 Reflect.construct()
 Reflect.defineProperty()
 Reflect.deeletProperty()
 Reflect.get()/set()
 Reflect.getOwnPropertyDescriptor()
 Reflect.getPrototypeOf()/setPrototypeOf()
 Reflect.has()
 Reflect.isExtensible()
 Reflect.ownKeys()
 Reflect.preventExtendsion()
78
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.apply(function, thisArg, args)
 Function.apply와 동일
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4
Reflect.apply("".charAt, "ponies", [3]);
// "i"
79
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.construct(function, args[, prototype])
 new 연산자와 비슷
 Reflect.defineProperty(object, property, descriptor)
 Object.defineProperty()와 비슷
var d = Reflect.construct(Date, [1776, 6, 4]);
d instanceof Date; // true
d.getFullYear(); // 1776
80
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.defineProperty(object, property, descriptor)
 Object.defineProperty()와 비슷
var obj = {};
Reflect.defineProperty(obj, "x", {value: 7}); // true
obj.x; // 7
81
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.deleteProperty(object, property)
 delete 연산자와 동일
var obj = { x: 1, y: 2 };
Reflect.deleteProperty(obj, "x"); // true
obj; // { y: 2 }
var arr = [1, 2, 3, 4, 5];
Reflect.deleteProperty(arr, "3"); // true
arr; // [1, 2, 3, , 5]
Reflect.deleteProperty({}, "foo"); // true
Reflect.deleteProperty(Object.freeze({foo: 1}), "foo"); // false
82
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.get(object, property[, thisObj])
 Reflect.set(object, property, value [, thisObj])
 객체 프로퍼티 값 접근 및 지정
var obj = { x: 1, y: 2 };
Reflect.get(obj, "x"); // 1
// Array
Reflect.get(["zero", "one"], 1); // "one"
var obj = {};
Reflect.set(obj, "prop", "value"); // true
obj.prop; // "value"
// Array
var arr = ["duck", "duck", "duck"];
Reflect.set(arr, 2, "goose"); // true
arr[2]; // "goose"
83
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.getOwnPropertyDescriptor(object, property)
 Object.getOwnPropertyDescriptor()와 유사
Reflect.getOwnPropertyDescriptor({x: "hello"}, "x");
// {value: "hello", writable: true, enumerable: true, configurable: true}
Reflect.getOwnPropertyDescriptor({x: "hello"}, "y");
// undefined
Reflect.getOwnPropertyDescriptor([], "length");
// {value: 0, writable: true, enumerable: false, configurable: false}
84
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.getPrototypeOf(object)
 Object.getPrototypeOf()와 동일
 Reflect.setPrototypeOf(object, prototype)
 Object.setPrototypeOf()와 도일
Reflect.setPrototypeOf({}, Object.prototype); // true
// It can change an object's [[Prototype]] to null.
Reflect.setPrototypeOf({}, null); // true
// Returns false if target is not extensible.
Reflect.setPrototypeOf(Object.freeze({}), null); // false
// Returns false if it cause a prototype chain cycle.
var target = {};
var proto = Object.create(target);
Reflect.setPrototypeOf(target, proto); // false
85
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.has(object, propertyKey)
 in 연산자와 비슷
Reflect.has({x: 0}, "x"); // true
Reflect.has({x: 0}, "y"); // false
// returns true for properties in the prototype chain
Reflect.has({x: 0}, "toString");
// Proxy with .has() handler method
obj = new Proxy({}, {
has(t, k) { return k.startsWith("door"); }
});
Reflect.has(obj, "doorbell"); // true
Reflect.has(obj, "dormitory"); // false
86
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Reflect
 Reflect.isExtensible()
 Object.isExtensible()과 동일
 Reflect.preventExtensions()
 Object.preventExtensions()와 동일
// Objects are extensible by default.
var empty = {};
Reflect.isExtensible(empty); // === true
// ...but that can be changed.
Reflect.preventExtensions(empty);
Reflect.isExtensible(empty); // === false
87
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
88
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Proxy
 new Proxy(target, handler)
 객체의 기본 동작에 사용자 임의 로직 적용 위한 wrapper 객체
 target : 대상 원본객체
 trap : target의 동작을 가로채는 함수
 handler : 트랩을 가지고 있는 객체, proxy에 적용
var target = { name: 'lee'};
var handler = {};
var proxy = new Proxy(target, handler);
proxy.age = 27;
console.log(proxy.name, proxy.age);
console.log(target.name, target.age);
89
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Proxy
 set/get
 set(target, property, value, recevier)
 get(target, property, recevier)
var target = { name: 'kim', age : 27};
var handler = {
set: function(target, property, value, receiver){
if(property === 'name'){
target[property] = 'Mr.' + value;
}else{
target[property] = value;
}
},
get : function(target, property, receiver){
if(property === 'age'){
return target[property] - 5;
}else{
return target[property];
}
}
};
var proxy = new Proxy(target, handler);
proxy.name = 'Lee';
console.log(proxy.name, proxy.age);
90
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Proxy
 construct(target, args)
 new 호출시 실행
var p = new Proxy(function() {}, {
construct: function(target, argumentsList, newTarget) {
console.log("called: " + argumentsList.join(", "));
return { value: argumentsList[0] * 10 };
}
});
console.log(new p(1).value); // "called: 1"
// 10
91
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
92
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Class
 Class
 prototype 기반 객체 지향을 손쉽게
 함수의 새로운 구문
 상속, overriding
 constructor, super
 hoisting 안됨
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
getArea(){
return this.height * this.width;
}
}
var p = new Polygon(100, 200);
p.getArea(); // 200000
93
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Class
 Static
 객체 생성 없이 호출
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
94
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Class
 상속
 extends
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
95
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Class
 super
 부로 클래스 접근
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
96
Copyright blog.xcoda.net
3.ES5 & ES6
1. ES5 Object
2. ES5 Array
3. ES5 String
4. ES5 기타
5. ES6 Syntax
6. ES6 Built-in APIs
7. ES6 Iterator
8. ES6 Promise
9. ES6 Reflect
10.ES6 Proxy
11.ES6 Class
12.ES6 Module
세부 목차
97
Copyright blog.xcoda.net
3.ES5 & ES6ES6 Module
 export
 모듈 작성시 기능을 제공
 import
 다른 모듈의 기능을 사용
import { cube, foo } from 'my-module';
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
// module "my-module.js"
export function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { foo };

Mais conteúdo relacionado

Mais procurados

파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403Yong Joon Moon
 
EcmaScript6(2015) Overview
EcmaScript6(2015) OverviewEcmaScript6(2015) Overview
EcmaScript6(2015) Overviewyongwoo Jeon
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기Yong Joon Moon
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409Yong Joon Moon
 
엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612Yong Joon Moon
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 Yong Joon Moon
 
엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613Yong Joon Moon
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)beom kyun choi
 
파이썬 언어 기초
파이썬 언어 기초파이썬 언어 기초
파이썬 언어 기초beom kyun choi
 
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자Donghyeok Kang
 
파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301Yong Joon Moon
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기Yong Joon Moon
 
파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310Yong Joon Moon
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQLPgDay.Seoul
 
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Leonardo YongUk Kim
 
파이썬 객체 클래스 이해하기
파이썬  객체 클래스 이해하기파이썬  객체 클래스 이해하기
파이썬 객체 클래스 이해하기Yong Joon Moon
 
python data model 이해하기
python data model 이해하기python data model 이해하기
python data model 이해하기Yong Joon Moon
 

Mais procurados (20)

파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403
 
Xe hack
Xe hackXe hack
Xe hack
 
EcmaScript6(2015) Overview
EcmaScript6(2015) OverviewEcmaScript6(2015) Overview
EcmaScript6(2015) Overview
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409
 
엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
 
엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613엘라스틱서치 이해하기 20160613
엘라스틱서치 이해하기 20160613
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)
 
파이썬 언어 기초
파이썬 언어 기초파이썬 언어 기초
파이썬 언어 기초
 
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#16.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
 
파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기
 
파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
 
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
 
파이썬 객체 클래스 이해하기
파이썬  객체 클래스 이해하기파이썬  객체 클래스 이해하기
파이썬 객체 클래스 이해하기
 
python data model 이해하기
python data model 이해하기python data model 이해하기
python data model 이해하기
 
Swt J Face 2/3
Swt J Face 2/3Swt J Face 2/3
Swt J Face 2/3
 

Semelhante a ECMA Script 5 & 6

스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리ETRIBE_STG
 
Jquery javascript_ed10
Jquery javascript_ed10Jquery javascript_ed10
Jquery javascript_ed10hungrok
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원탑크리에듀(구로디지털단지역3번출구 2분거리)
 
ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!WooYoung Cho
 
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdfHyosang Hong
 
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Circulus
 
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Node.js and react
Node.js and reactNode.js and react
Node.js and reactHyungKuIm
 
JavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsJavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsHyuncheol Jeon
 
Javascript - Array
Javascript - ArrayJavascript - Array
Javascript - Arraywonmin lee
 
Collection framework
Collection frameworkCollection framework
Collection frameworkssuser34b989
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304Yong Joon Moon
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storageJinKyoungHeo
 

Semelhante a ECMA Script 5 & 6 (20)

자바스크립트 클래스의 프로토타입(prototype of class)
자바스크립트 클래스의  프로토타입(prototype of class)자바스크립트 클래스의  프로토타입(prototype of class)
자바스크립트 클래스의 프로토타입(prototype of class)
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리
 
Jquery javascript_ed10
Jquery javascript_ed10Jquery javascript_ed10
Jquery javascript_ed10
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!
 
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#17.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdf
 
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
Startup JavaScript 5 - 객체(Date, RegExp, Object, Global)
 
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
Nodejs express
Nodejs expressNodejs express
Nodejs express
 
JavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsJavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and Constructors
 
Javascript - Array
Javascript - ArrayJavascript - Array
Javascript - Array
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Hacosa j query 4th
Hacosa j query 4thHacosa j query 4th
Hacosa j query 4th
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storage
 

Último

Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Kim Daeun
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Wonjun Hwang
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Wonjun Hwang
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionKim Daeun
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)Tae Young Lee
 

Último (6)

Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
 
캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)
 

ECMA Script 5 & 6

  • 1. 1 Copyright blog.xcoda.net ES5 & ES6 Rev. JS303 이세우 (dltpdn@gmail.com, blog.xcoda.net) 기업 및 영리를 목적으로 하는 교육에 허락 없이 사용할 수 없습니다.
  • 2. 2 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 3. 3 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 정의  Object.defineProperty(obj, prop, desc), defineProperties(obj, props)  Data Descriptor  value : 속성 값(*undefined)  writable : {true|*false}, 쓰기(값의 할당)금지 여부  enumerable : {true|*false}, for-in문, keys() 출력 여부  configurable :{true|*false}, 제거 및 설정변경 여부  Access Descriptor  set : {function | *undefined}, 인자의 값이 속성의 값  get : {function | *undefined} , 함수의 반환값이 속성의 값  Data descript와 Access Descriptor 는 동시에 정의 불가  Object.getOwnPropertyDescriptor(obj, prop)
  • 4. 4 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 정의  Data Descriptor var obj = {}; Object.defineProperty(obj, 'name', { value :'lee' writable : false, enumerable : false }); obj.name; // 'lee' obj.name = 'kim'; // no effect or error in strict mode delete obj.name; // false for(var key in obj){ //no loop execution console.log(key); } Object.getOwnPropertyDescriptor(obj, 'name');
  • 5. 5 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 정의  Access Descriptor function Person(name, age){ var _name =name; var _age = age; Object.defineProperty(this, 'name', { get: function(){ console.log('get name'); return _name; }, set : function(name){ console.log('set name'); _name = name; } }); Object.defineProperty(this, 'age', { set : function(age){ console.log('set age'); _age = age; }, get : function(){ console.log('get age'); return _age; } }); }; Person lee = new Person('lee', 27); lee.name = 'kim'; lee.age = 23; console.log(lee.name); // 'kim' console.log(lee.age); // 23
  • 6. 6 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 정의  Getter/Setter Accessor  { get prop(){...} } var value = 0; var obj = { get v(){ console.log('getter.'); return value; }, set v(v){ console.log('setter:'+v); value = v; } }; obj.v = 10; // setter:10 console.log(obj.v); // gettter. 10
  • 7. 7 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  descriptor 변경  정의된 속성의 writable/configurable/enumarable 변경  configurable = false 인경우 Error var obj = {}; Object.defineProperty(obj, 'name', { value :'lee' writable : true }); var desc = Object.getOwnPropertyDescriptor(obj, 'name'); desc.writable = false; Object.defineProperty(obj, 'name', desc);
  • 8. 8 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 정의  Object.defineProperties(obj, props) : 여러 속성을 한번에 정의 var obj = {}; Object.defineProperties(obj, {'name', { value :'lee', writable : false, enumerable : false }, 'age', { value : 27, writeable : true, enumerable : true } } );
  • 9. 9 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 확장 제어  Property 동적 추가 불가  Object.preventExtensions( obj )  Object.isExtensionsible( obj) var obj = {}; Object.preventExtensions(obj); Object.isExtensionsible(obj); // true obj.name = 'lee'; // 효력 없음, Error in strict mode Object.defineProperty(obj, 'name', { value :'lee' writable : false, enumerable : false }); // Error
  • 10. 10 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 봉인  Object.seal(obj)  Object.isSeal(obj)  모든 속성의 descriptor의 변경 불가  preventExtensions() + 모든 속성에 대해서 configurable = false  구현 사례 Object.seal = function( obj ) { var props = Object.getOwnPropertyNames( obj ); for ( var i = 0; i < props.length; i++ ) { var desc = Object.getOwnPropertyDescriptor( obj, props[i] ); desc.configurable = false; Object.defineProperty( obj, props[i], desc ); } return Object.preventExtensions( obj ); };
  • 11. 11 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 Freezing  Object.freeze(obj)  Object.isFrozen(obj)  객체 속성의 확장, writable, configurable 불가  Seail + (writable = false)  구현 사례 Object.freeze = function( obj ) { var props = Object.getOwnPropertyNames( obj ); for ( var i = 0; i < props.length; i++ ) { var desc = Object.getOwnPropertyDescriptor( obj, props[i] ); if ( "value" in desc ) { desc.writable = false; } desc.configurable = false; Object.defineProperty( obj, props[i], desc ); } return Object.preventExtensions( obj ); };
  • 12. 12 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 생성 및 상속  Object.create( parent, propDesc )  지정한 객체를 상속받는 객체 생성  property descriptor를 지정 function Person(name, age){ this.name = name; } Person.prototype.getName = function(){ return this.name; } var parent = new Person('lee'); var child = Object.create(parent, {'age': { value :27 } }); child.getName(); // 'lee' child.age; // 27
  • 13. 13 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 생성 및 상속  Object.create( parent, propDesc )  구현 사례 Object.create = function( proto, props ) { var ctor = function( ps ) { if ( ps ) Object.defineProperties( this, ps ); }; ctor.prototype = proto; return new ctor( props ); };
  • 14. 14 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 속성 조사  Object.keys( obj ) :  enumarable 속성을 배열로 반환  Object.getOwnPropertyNames( obj ) :  직접 소유한 속성을 배열로 반환  Object.getOwnPropertyDescriptor( obj , 'prop name') :  지정한 속성에 대한 descriptor를 반환 var obj = {name: 'lee', age : 27}; Object.defineProperty(obj, 'addr', { value:'seoul', enumarable:false }); Object.keys(obj); // [name, age] Object.getOwnPropertyNames(obj); //[name, age, addr]
  • 15. 15 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Object  객체 관련 기타 사항  마지막 콤마(,) 허용  JSON 객체의 마지막 속성  배열 요소의 마지막 요소  예약어(key word)를 속성으로 사용 가능 var obj = {name: 'lee', age : 27, }; var array = [1,2,3,4,5,] obj.if = 'interface'; obj.var = 4
  • 16. 16 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array 기능 확대  Array.isArray()  .indexOf(seachElement [, fromIndex=0]), lastIndexOf()  .forEach()  .every(callback [, thisArg]);  .some()  .filter()  .map()  .reduce()  .reduceRight()
  • 17. 17 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  Array.isArray()  배열 여부 확인 Array.isArray([]); //true Array.isArray([1]); //true Array.isArray(new Array()); //true Array.isArray({}); // false Array.isArray(10); //false Array.isArray(); //false Array.isArray(undefined); // false
  • 18. 18 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .indexOf(seachElement [, fromIndex=0])  .lastIndexOf(seachElement [, fromIndex=0])  배열 요소 검색  반환 : not found : -1  fromIndex  검색을 시작할 index  음수인 경우 배열 끝에서 부터 offset, 검색은 앞에서 뒤로  (역방향 검색 아님) var array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
  • 19. 19 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .forEach(callback [, thisArg]);  callback(currentElement, index, array)  배열의 모든 요소에 대해서 callback 함수 호출  초기화 되지 않거나 삭제된 요소에 대해서는 호출 생략 [3,2,9,1].forEach(function(el, idx, array){ console.log(idx +":" + el); }); //0:3 //1:2 //2:9 //4:1
  • 20. 20 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .every(callback [, thisArg]);  callback(currentElement, index, array)  배열의 모든 요소가 callback함수의 조건을 만족하는지 확인 function isBigEnough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true
  • 21. 21 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .some(callback [, thisArg]);  callback(currentElement, index, array)  배열의 모든 요소 중 하나라도 callback함수의 조건을 만족하는지 확인 function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true var fruits = ['apple', 'banana', 'mango', 'guava']; function checkAvailability(arr, val) { return arr.some(function(arrVal) { return val === arrVal; }); } checkAvailability(fruits, 'kela'); //false checkAvailability(fruits, 'banana'); //true
  • 22. 22 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .filter(callback [, thisArg]);  callback(currentElement, index, array)  callback함수의 조건을 만족하는 요소들로 구성된 새로운 배열 생성 function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]
  • 23. 23 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .map(callback [, thisArg]);  callback(currentElement, index, array)  배열의 모든 요소에 대해서 callback함수의 결과 값을 갖는 새로운 배열 생성 [1, 2, 3].map(function(el, idx, array){ return el * el; }); //[ 1, 4, 9 ] ['1', '2', '3'].map(function(el, idx, array){ return parseInt(el, 10); }); // [1, 2, 3] ['1', '2', '3'].map(Number); //[1,2,3]
  • 24. 24 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .reduce (callback [, initialValue]);  callback(preElement, currentElement, index, array)  index 1에서 부터 실행  pre : 최초 실행시 0번째 요소, 이후는 이전 callback의 반환값 [0, 1, 2, 3, 4].reduce(function(pre, curr, idx, array) { return pre + curr; }); // 10 호출횟수 pre curr idx return 1 0 1 1 1 2 1 2 2 3 3 3 3 3 6 4 6 4 4 10
  • 25. 25 Copyright blog.xcoda.net 3.ES5 & ES6ES5 Array  Array  .reduceRight(callback [, initialValue]);  callback(preElement, currentElement, index, array)  reduce 호출을 배열 요소의 오른쪽에서 부터 [0, 1, 2, 3, 4].reduce(function(pre, curr, idx, array) { return pre + curr; }); // 10 호출횟수 pre curr idx return 1 4 3 3 7 2 7 2 2 9 3 9 1 1 10 4 10 0 0 10
  • 26. 26 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 27. 27 Copyright blog.xcoda.net 3.ES5 & ES6ES5 String  String  .trim()  앞뒤 공백(space, tab, 줄바꿈 기호) 제거  프로퍼트 접근  인덱스를 프로퍼티 이름으로 접근 var str = ' abc '; console.log(str.trim()); // 'abc' var str2 = 'abc'; str2[2]; // 'c'
  • 28. 28 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 29. 29 Copyright blog.xcoda.net 3.ES5 & ES6ES5 기타  Function  .bind(thisArg [ , arg1, arg2...]);  함수 호출에 사용할 this 객체를 지정하여 새로운 함수 반환  call()/applay()는 호출할 때 마다 지정 var obj = {name: 'lee'}; function f(){ return this.name; } f(); // undefined var obj_f = f.bind(obj); obj_f(); // 'lee'
  • 30. 30 Copyright blog.xcoda.net 3.ES5 & ES6ES5 기타  Date  new Date( ISOString),  .toISOString()  .now()  JSON  JSON.parse()  JSON.stringify()
  • 31. 31 Copyright blog.xcoda.net 3.ES5 & ES6ES5 기타  Strict Mode  ECMAScript 3 기능 중 Deprecated 된 것을 사용할 수 없게 한다.  정의되지 않은 변수에 할당 불가  객체 Property의 변경 불가(아래의 경우)  writable=false , 수정 불가  configurable= false, 삭제 불가  extensible=false, 추가 불가  Eval  eval을 ID로 사용 불가  eval() 함수 내에서 변수 선언 불가  Function  arguments 객체에 할당 불가  arguments.callee 사용 불가  arguments.caller 사용 불가  with(){} 구문 사용 불가 <script type="text/javascript> "use strict" ... //or function imStrict(){ "use strict" // code here.... }
  • 32. 32 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 33. 33 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  변수 선언  let  block scope 변수 선언  재정의 불가  var은 funciton scope 변수 선언 var a = 1; var a = 10; // OK console.log(a); // 10 let b = 1; let b = 10; // Error function f(){ var x = 10; let y = 20; } console.log(x); // 10 console.log(y); // Error, not defined
  • 34. 34 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  변수 선언  const  상수 선언  값의 재할당 금지  let 과 동일한 scope 정책  객체 참조의 경우 객체 자체는 가변(C 언어와 차이) const V = 10; V = 20; // Error const OBJ = { name : 'lee'}; OBJ.name = 'kim'; // OK OBJ = {name:'kim'}; // Error
  • 35. 35 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Default Parameter  함수의 매개변수에 기본 값 지정  undefined 값의 전달 기본 값 적용  old style  ES6 style function f(x, y, z){ x = x || 1; y = y || 2; z = z || 3; console.log(x, y, z); } f(10, 20); // 10, 20, 3 function f(x = 1, y = 2, z = 3){ console.log(x, y, z); } f(10, 20); // 10, 20, 3
  • 36. 36 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Spread Operator(펼침 연산자) : ...arg  배열과 같은 Iterable 객체의 요소  함수에 전달 할때 개별 항으로 취급  old style  ES6 style function f(a, b){ return a + b; } var array = [2, 3]; f(array[0], array[1]); // 5 f.apply(null, array);//5 function f(a, b){ return a + b; } var array = [2, 3]; f(...array);//5
  • 37. 37 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Spread Operator(펼침 연산자) : ...arg  부분 배열  배열 합치기 let array1 = [1,2,3]; let array2 = [0, ...array1, 4,5,6,] // [0, 1,2,3,4,5,6] let array1 = [1,2,3]; let array2 = [4,5]; array1.push(...array2); // [1,2,3,4,5]
  • 38. 38 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Rest Operator(나머지 연산자) : ...arg  함수 선언부의 마지막 파라미터에 "..." 작성  지정된 파리미터 이외의 값을 배열형식으로 전달 function f(a, b, ...args){ console.log(args); } f(1,2,3,4,5); //[3,4,5]
  • 39. 39 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Destructuring Assignment(해체 할당)  Iterable/Object 각각의 요소/속성을 여러 변수에 한번에 할당  배열 해체 할당 var array = [1,2,3]; var a = array[0]; var b = array[1]; var c = array[2]; var x,y,z; [x,y,z] = array;// x:1, y:2, z :3 var [aa, bb, cc] = array;// aa:1, bb:2, cc:3
  • 40. 40 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Destructuring Assignment(해체 할당)  값 건너 뛰기  나머지 연산자  기본값 할당  파라미터로 해체 할당 let [a, , b] = [1,2,3]; // a:1, b:3 let [a, ...b] = [1,2,3,4,5]; //a:1, b:[2,3,4,5] let [a, b, c = 3] = [1,2]; // a:1, b:2, c:3 function f([a,b,c=3] = [1,2,3]){ ... }; f(undefined);
  • 41. 41 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Destructuring Assignment(해체 할당)  객체 해체 할당  객체 프로퍼티를 각각의 개별 변수에 할당  프로퍼티와 변수의 이름을 갖게 var obj = {name:'lee', age:27}; var name, age; ({name, age} = obj); console.log(name, age); // 'lee', 27 var a, b; ({name:a, age:b} = obj); console.log(a, b); // 'lee', 27 var {name:x, age:y} = obj; console.log(x, y); //'lee', 27
  • 42. 42 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Arrow Function  람다 식, 익명 함수  (parameter)=>{ ... body...}  함수 body의 문이 한줄 이면 return 과 {} 생략 가능  파라미터가 1개 이면 () 생략 가능  파라미터 없으면 () 생략 불가 (param1, param2, ..., paramN) => { statements } (param1, param2, ..., paramN) => expression (singleParam) => { statements } singleparam => { statements } () => { statements } var plus = (a,b)=>{ return a+b}; plus(1, 2); //3 var plus = (a, b)=> a+b; plus(3, 4); // 7
  • 43. 43 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Arrow Function  Lexical this  일반 함수와 같이 this 사용 불가  바깥 함수의 this를 사용 var obj = { name: 'lee', getName: function(){ return this.name;}}; obj.getName(); // 'lee' var obj2 = {name: 'lee', getName: ()=>this.name}; obj2.getName(); //undefined var obj3 = {name:'lee', getName:function(){ return (()=>this.name)(); }} obj3.getName(); // 'lee'
  • 44. 44 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Arrow Function  Lexical this  일반 함수와 같이 this 사용 불가  바깥 함수의 this를 사용  생성자 사용 불가(new 사용 불가) var obj = { name: 'lee', getName: function(){ return this.name;}}; obj.getName(); // 'lee' var obj2 = {name: 'lee', getName: ()=>this.name}; obj2.getName(); //undefined var obj3 = {name:'lee', getName:function(){ return (()=>this.name)(); }} obj3.getName(); // 'lee' var arrow = () => 'hello'; new arrow(); // Error
  • 45. 45 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Syntax  Object literal  편리한 프로퍼티 값 할당  편리한 메서드 정의  computed property name(조합 프로퍼티명) var name = 'lee', age = 27; var obj = {name, age}; var obj = { hello(){ console.log('hello world'); } }; obj.hello(); // 'hello world' var obj = { ['last' + 'name'] : 'lee'}; obj.lastname; // 'lee'; obj['last' + 'name']; //'lee'
  • 46. 46 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 47. 47 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Number  2진수 리터럴 :  0b  8진수 리터럴  ES5 :0  ES6 : 0o  isInteger() :  정수 판별 let bi = 0b00001111; console.log( bi === 15, bi); // true 15 let oct = 010; // 8 let oct2 = 0o10; // 8 Number.isInteger(123);//true Number.isInteger(3.14);//false Number.isInteger("123");//false Number.isInteger("abc");//false
  • 48. 48 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Number  isNaN() :  NaN 판별 : 오직 NaN만 true  global.isNaN() : 숫자로 변환할 수 없으면 모두 true  isFinite() :  유한숫자 판별 : 오직 숫자만 true  global.isFinite() : 숫자로 변환 할 수 있으면 true isNaN(123);// false isNaN('123');// false isNaN('abc'); //true isNaN(NaN); // true Number.isNaN(123);// false Number.isNaN('123');//false Number.isNaN('abc');//false Number.isNaN(NaN); // true isFinite(10); //true isFinite(null); //true isFinite('');//true isFinite(1/0); //false Number.isFinite(10);//true Number.isFinite(null); // false Number.isFinite(''); // false Number.isFinite(1/0); // false
  • 49. 49 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Number  Number.EPSILON  약 2-52  부동 소수점의 미세한 오차 무시하는데 사용 console.log(0.1 + 0.2);// 0.30000000000000004 console.log(0.1 + 0.2 == 0.3);// false function epsilonEqual(a, b){ return Math.abs(a-b) < Number.EPSILON; } console.log(epsilonEqual(0.1+0.2, 0.3));//true
  • 50. 50 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Math  삼각 연산  하이퍼 볼릭  Math.sinh(), Math.cosh(), Math.tanh(),  역 하이퍼 볼릭  Math.asinh(), Math.acosh(), Math.atanh()  피타고라스 정리  Math.hypot()  산술 연산  Math.log2(), Math.log10(), Math.log1p(), Math.expm1(), math.cbrt()  32비트  Math.imul(), Math.clz32()  기타  Math.sign() : 양수 음수 구분, 1, 0, -1로 반환  Math.trunc() : 가수부 덜어낸 정수부 반환  Math.fround() : 32비트 부동 소수점 값으로 반올림
  • 51. 51 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  String  .repeat(times) : 지정한 횟수 만큼 연결  includes(string[, index]) : 지정한 문자열 포함 여부  startsWith(str[, index]), endsWith(str[, index]) console.log('z'.repeat(6));//zzzzzz var s = 'hello world'; s.includes('hello'); //true var s = 'hello world'; s.includes('hello'); //true
  • 52. 52 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  String  template 문자열  역 따옴표(`)  place holder : ${}  multi line string  tagged template var name = 'Lee', age = 27; var template = `Hello! my name is ${name}, ${age} years old`; console.log(template);// 'Hello! my name is Lee, 27 years old' function tag(strings, ...values){ console.log(strings); console.log(values); return strings[0] + strings[1] + (values[0] + values[1]); } var a=10, b=20; var temp = tag `hello ${a} world ${b}`; // 'hello world 30'
  • 53. 53 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Array  Array.from(iterable [, callback[, thisArg]])  callback(value, idx)  배열 비슷한 객체를 배열로 생성  iterable  length 속성을 갖음  index로 요소 접근 Array.from([1, 2, 3], x => x + x); // [2, 4, 6] Array.from({length:5}, (val, idx)=>{ console.log(val, idx); return idx }); undefined 0 undefined 1 undefined 2 undefined 3 undefined 4 [ 0, 1, 2, 3, 4 ]
  • 54. 54 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Array  Array.of(element0 [, element n]);  주어진 요소로 배열 생성  new Array()와 차이  .fill(value [, start=0 [, end = length]])  지정된 값으로 배열을 채운다. new Array(5); //[ ,,,,], length:5 Array.of(5); // [5], length:1 Array.of(1,2,3); //[1,2,3], length:3 [1, 2, 3].fill(4); // [4, 4, 4] [1, 2, 3].fill(4, 1); // [1, 4, 4] [1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
  • 55. 55 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Array  .find(callback, thisArg)  callback을 만족하는 요소 반환  callback(value, index, array)  .findIndex(callback, thisArg)  find와 동일, 값이 아닌 index 반환 var people = [ {name:'lee', age:27}, {name:'kim', age:23}, {name:'park', age:30} ]; people.find(function(val, idx, arr){ return val.name = 'kim'; }); //{ name: 'kim', age: 27 }
  • 56. 56 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Array  .copyWithin(target, start[, end = this.length)  배열 내 요소를 다른 위치에 복사  entries(), keys(), values()  배열을 iterable 객체로 반환 [1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(0, 3, 4); // [4, 2, 3, 4, 5] var entries = [1,2,3].entries(); console.log(...entries); //[0, 1] [1, 2] [2, 3] var keys = [1,2,3].keys(); // 0 1 2 console.log(...keys); var values = [1,2,3].values(); console.log(values); // 1 2 3
  • 57. 57 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  ArrayBuffer  new ArrayBuffer(length) , length : byte  고정 길이 binary data  1Byte 데이타 블록 하나가 원소  Typed Array 또는 DataView를 이용  DataView(buffer [, byteOffset [, byteLength]])  ArrayBuffer에 숫자를 읽고 쓰기 위한 인터페이스  setXXX(offset, value, bigEndian), getXXX(offset, bigEndian);  set/getInt8, set/getUint8, set/getInt16, set/getUint16  set/getInt32, set/getUint32, set/getFloat32, set/getFloat64 let buff = new ArrayBuffer(80); let view = DataView(buff); view.setInt32(8, 22, false); var number = view.getInt32(8, false); console.log(number);//22
  • 58. 58 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Typed Array  DataView의 offset 계산을 편리하게 위한 wrapper  Int8Array, Uint8Array, Int16Array, Uint16Array  Int32Array, Uint32Array, Float32Array, Float64Array  new XXArray(buffer [, byteOffset [, length]])  new XXArray(length)  new XXArray(array) let buff = new ArrayBuffer(80); let typed = new Int32Array(buff); typed[0] = 22; console.log(typed.length, typed[0]); // 20 22 let int16 = new Int16Array(2); int16[0] = 10; int16[1] = 20; console.log(int16); // {0=10, 1=20} let x = new Int16Array([21, 31]); console.log(x); // {0=21, 1=31}
  • 59. 59 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Set  new Set([iterable])  값의 중복을 허용하지 않는 컬렉션 var myset = new Set(); myset.add(1); myset.add(5); myset.add('hello'); var obj = {name:'lee'}; myset.add(obj); myset.has(1); // true myset.has(3); // false myset.has(5); // true myset.has("hello"); //true myset.size; //4 myset.delete(5); // true myset.has(5); // false myset.size; //3
  • 60. 60 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Map  new Map([iterable])  key : value 쌍으로 저장 let map = new Map(); map.set("name", 'lee'); map.set("age", 27); map.size; // 2 for (var [key, value] of map) { console.log(key + " = " + value); } map.has("name"); // true map.get("age"); // 27 map.delete("age"); //true map.size; //1 map.clear();
  • 61. 61 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  WeakSet  Object 만 저장 가능  weekly held object reference  저장된 객체에 대한 다른 참조가 없으면 garbage collection  WeakMap  Object 만 저장 가능  weekly held object reference  저장된 객체에 대한 다른 참조가 없으면 garbage collection
  • 62. 62 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Built-in APIs  Object  Object.is(value1, value2)  두 값의 동등 여부 판단  === 과 차이  Object.assign(target, ...sources)  source의 프로퍼티를 target에 복사 0 === -0; // true Object.is(0, -0); //false NaN === NaN; //false Object.is(NaN, NaN); //true NaN === 0/0; //false Object.is(NaN, 0/0); true var obj = {name:'lee'}; var obj2 = {age : 27}; Object.assign(obj, obj2); obj.name; // 'lee' obj.age; // 27
  • 63. 63 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 64. 64 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Iterator  Symbol  Symbol([descriptor])  유일한 값 생성  ES6에서 추가된 primitive type  객체의 property key로 사용  new 키워드 사용 불가  Object.getOwnPropertySymbols()  getOwnPropertyNames()에 대응하는 함수 var sym1 = Symbol(); var sym2 = Symbol(); sym1 === sym2; //false var obj = {[sym1] : 1}; obj[sym1];// 1 Object.getOwnPropertySymbos(obj);// Symbol()
  • 65. 65 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Iterator  Symbol  Symbol.for("key")  "key"에 해당하는 Symbol을 생성하거나 반환한다.  전역 영역의 registry, Symbol()의 scope 문제 해결  Well-known symbol  이미 만들어 놓은 symbol  Symbol.iterator  Symbol.match let obj = {}; (function(){ let s1 = Symbol(); obj[s1] = 'lee'; })(); obj[s1];// Error let obj = {}; (function(){ let s1 = Symbol.for("name"); obj[s1] = 'lee'; })(); obj[Symbol.for("name")]; // 'lee'
  • 66. 66 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Iterator  Iterator protocol  next 함수 제공  value, done 프러퍼티를 갖는 객체 반환  value : 다음 값, done: 순회 끝 여부  Iterable protocol  Symbol.iterator를 키로 하는 Iterator protocol을 만족하는 함수 구현  @@iterator let obj = { array: [ 1,2,3,4], nextIndex : 0, [Symbol.iterator] : function(){ return { array: this.array, next: function(){ return this.nextIndex < this.array.length ? {value : this.array[this.nextIndex++], done:false}: {done:true}; } } } }
  • 67. 67 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Iterator  Generator  function*  재 진입 가능 함수  매 next()마다 다음 yield 지점까지만 실행 function* idMaker(){ var index = 0; while(index < 3) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // undefined
  • 68. 68 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Iterator  for ... of loop  for( variable of iterable)  next()호출을 자동으로 진행 let iterable = [1, 2, 3]; for (let value of iterable) { console.log(value); } // 1 // 2 // 3
  • 69. 69 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 70. 70 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise  new Promise(function(resolve, reject){ ... })  excutor  이행하면 resolve, 거절하면 reject  인스턴스 상태  pending : 초기상태  fulfilled : 성공  rejected : 실패  settled : 종료  then(onFullfilled, onRejected)  catch(), all()
  • 71. 71 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise  then() var doAsync = function(condition){ return new Promise(function(resolve, reject){ setTimeout(function(){ if(condition){ resolve("success"); }else{ reject("fail"); } }, 3000); } }; doAsync(true).then(function(value){ console.log('ok:' + value); }, function(reason){ console.log('fail:' + reason); });
  • 72. 72 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise  then(), catch() var doAsync = function(condition){ return new Promise(function(resolve, reject){ setTimeout(function(){ if(condition){ resolve("success"); }else{ reject("fail"); } }, 3000); } }; doAsync(true).then(function(value){ console.log('ok:' + value); }).catch(function(reason){ console.log('fail:' + reason); });
  • 73. 73 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise  chainning  No return : 새로운 fulfilled Promise 객체 생성 연결  return new Promise : new Promise 객체 연결  return value : new Promise 객체 연결 asyncThing1() .then(function() { return asyncThing2();}) .then(function() { return asyncThing3();}) .catch(function(err) { return asyncRecovery1();}) .then(function() { return asyncThing4();}, function(err) { return asyncRecovery2(); }) .catch(function(err) { console.log("Don't worry about it");}) .then(function() { console.log("All done!");});
  • 74. 74 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise.all()  모든 비동기 작업이 끝나면 var promise1 = new Promise(function (resolve, reject) { setTimeout(function () { console.log("첫번째 Promise 완료"); resolve("11111"); }, Math.random() * 20000 + 1000); }); var promise2 = new Promise(function (resolve, reject) { setTimeout(function () { console.log("두번째 Promise 완료"); resolve("222222"); }, Math.random() * 10000 + 1000); }); Promise.all([promise1, promise2]).then(function (values) { console.log("모두 완료됨", values); });
  • 75. 75 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Promise  Promise.race()  모든 비동기 작업 중 하나라도 완료되면 var promise1 = new Promise(function (resolve, reject) { setTimeout(function () { console.log("첫번째 Promise 완료"); resolve("11111"); }, Math.random() * 20000 + 1000); }); var promise2 = new Promise(function (resolve, reject) { setTimeout(function () { console.log("두번째 Promise 완료"); resolve("222222"); }, Math.random() * 10000 + 1000); }); Promise.race([promise1, promise2]).then(function (values) { console.log("하나 완료됨", values); });
  • 76. 76 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 77. 77 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect  동적인 객체와 함수에 대한 조작  Object API와 중복되는 것을 보완 및 정리한 API  new 연산자 사용 불가  함수 호출 불가  Reflect.apply()  Reflect.construct()  Reflect.defineProperty()  Reflect.deeletProperty()  Reflect.get()/set()  Reflect.getOwnPropertyDescriptor()  Reflect.getPrototypeOf()/setPrototypeOf()  Reflect.has()  Reflect.isExtensible()  Reflect.ownKeys()  Reflect.preventExtendsion()
  • 78. 78 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.apply(function, thisArg, args)  Function.apply와 동일 Reflect.apply(Math.floor, undefined, [1.75]); // 1; Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); // "hello" Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index; // 4 Reflect.apply("".charAt, "ponies", [3]); // "i"
  • 79. 79 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.construct(function, args[, prototype])  new 연산자와 비슷  Reflect.defineProperty(object, property, descriptor)  Object.defineProperty()와 비슷 var d = Reflect.construct(Date, [1776, 6, 4]); d instanceof Date; // true d.getFullYear(); // 1776
  • 80. 80 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.defineProperty(object, property, descriptor)  Object.defineProperty()와 비슷 var obj = {}; Reflect.defineProperty(obj, "x", {value: 7}); // true obj.x; // 7
  • 81. 81 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.deleteProperty(object, property)  delete 연산자와 동일 var obj = { x: 1, y: 2 }; Reflect.deleteProperty(obj, "x"); // true obj; // { y: 2 } var arr = [1, 2, 3, 4, 5]; Reflect.deleteProperty(arr, "3"); // true arr; // [1, 2, 3, , 5] Reflect.deleteProperty({}, "foo"); // true Reflect.deleteProperty(Object.freeze({foo: 1}), "foo"); // false
  • 82. 82 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.get(object, property[, thisObj])  Reflect.set(object, property, value [, thisObj])  객체 프로퍼티 값 접근 및 지정 var obj = { x: 1, y: 2 }; Reflect.get(obj, "x"); // 1 // Array Reflect.get(["zero", "one"], 1); // "one" var obj = {}; Reflect.set(obj, "prop", "value"); // true obj.prop; // "value" // Array var arr = ["duck", "duck", "duck"]; Reflect.set(arr, 2, "goose"); // true arr[2]; // "goose"
  • 83. 83 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.getOwnPropertyDescriptor(object, property)  Object.getOwnPropertyDescriptor()와 유사 Reflect.getOwnPropertyDescriptor({x: "hello"}, "x"); // {value: "hello", writable: true, enumerable: true, configurable: true} Reflect.getOwnPropertyDescriptor({x: "hello"}, "y"); // undefined Reflect.getOwnPropertyDescriptor([], "length"); // {value: 0, writable: true, enumerable: false, configurable: false}
  • 84. 84 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.getPrototypeOf(object)  Object.getPrototypeOf()와 동일  Reflect.setPrototypeOf(object, prototype)  Object.setPrototypeOf()와 도일 Reflect.setPrototypeOf({}, Object.prototype); // true // It can change an object's [[Prototype]] to null. Reflect.setPrototypeOf({}, null); // true // Returns false if target is not extensible. Reflect.setPrototypeOf(Object.freeze({}), null); // false // Returns false if it cause a prototype chain cycle. var target = {}; var proto = Object.create(target); Reflect.setPrototypeOf(target, proto); // false
  • 85. 85 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.has(object, propertyKey)  in 연산자와 비슷 Reflect.has({x: 0}, "x"); // true Reflect.has({x: 0}, "y"); // false // returns true for properties in the prototype chain Reflect.has({x: 0}, "toString"); // Proxy with .has() handler method obj = new Proxy({}, { has(t, k) { return k.startsWith("door"); } }); Reflect.has(obj, "doorbell"); // true Reflect.has(obj, "dormitory"); // false
  • 86. 86 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Reflect  Reflect.isExtensible()  Object.isExtensible()과 동일  Reflect.preventExtensions()  Object.preventExtensions()와 동일 // Objects are extensible by default. var empty = {}; Reflect.isExtensible(empty); // === true // ...but that can be changed. Reflect.preventExtensions(empty); Reflect.isExtensible(empty); // === false
  • 87. 87 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 88. 88 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Proxy  new Proxy(target, handler)  객체의 기본 동작에 사용자 임의 로직 적용 위한 wrapper 객체  target : 대상 원본객체  trap : target의 동작을 가로채는 함수  handler : 트랩을 가지고 있는 객체, proxy에 적용 var target = { name: 'lee'}; var handler = {}; var proxy = new Proxy(target, handler); proxy.age = 27; console.log(proxy.name, proxy.age); console.log(target.name, target.age);
  • 89. 89 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Proxy  set/get  set(target, property, value, recevier)  get(target, property, recevier) var target = { name: 'kim', age : 27}; var handler = { set: function(target, property, value, receiver){ if(property === 'name'){ target[property] = 'Mr.' + value; }else{ target[property] = value; } }, get : function(target, property, receiver){ if(property === 'age'){ return target[property] - 5; }else{ return target[property]; } } }; var proxy = new Proxy(target, handler); proxy.name = 'Lee'; console.log(proxy.name, proxy.age);
  • 90. 90 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Proxy  construct(target, args)  new 호출시 실행 var p = new Proxy(function() {}, { construct: function(target, argumentsList, newTarget) { console.log("called: " + argumentsList.join(", ")); return { value: argumentsList[0] * 10 }; } }); console.log(new p(1).value); // "called: 1" // 10
  • 91. 91 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 92. 92 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Class  Class  prototype 기반 객체 지향을 손쉽게  함수의 새로운 구문  상속, overriding  constructor, super  hoisting 안됨 class Polygon { constructor(height, width) { this.height = height; this.width = width; } getArea(){ return this.height * this.width; } } var p = new Polygon(100, 200); p.getArea(); // 200000
  • 93. 93 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Class  Static  객체 생성 없이 호출 class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); console.log(Point.distance(p1, p2));
  • 94. 94 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Class  상속  extends class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } }
  • 95. 95 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Class  super  부로 클래스 접근 class Cat { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Lion extends Cat { speak() { super.speak(); console.log(this.name + ' roars.'); } }
  • 96. 96 Copyright blog.xcoda.net 3.ES5 & ES6 1. ES5 Object 2. ES5 Array 3. ES5 String 4. ES5 기타 5. ES6 Syntax 6. ES6 Built-in APIs 7. ES6 Iterator 8. ES6 Promise 9. ES6 Reflect 10.ES6 Proxy 11.ES6 Class 12.ES6 Module 세부 목차
  • 97. 97 Copyright blog.xcoda.net 3.ES5 & ES6ES6 Module  export  모듈 작성시 기능을 제공  import  다른 모듈의 기능을 사용 import { cube, foo } from 'my-module'; console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 // module "my-module.js" export function cube(x) { return x * x * x; } const foo = Math.PI + Math.SQRT2; export { foo };