티스토리 뷰

WEB 웹/JAVASCRIPT

ECMAScript6

KIMSG 2017. 11. 24. 12:33
JavaScript가 프로토타입 기반의 OOP 인 줄은 사실 잘 몰랐다.
위키백과 : 자바스크립트(영어: JavaScript)는 객체 기반의 스크립트 프로그래밍 언어이다. 이 언어는 웹브라우저 내에서 주로 사용하며, 다른 응용 프로그램의 내장 객체에도 접근할 수 있는 기능을 가지고 있다.

이런 부분에서 js를 많이 배워두면 좋을 것 같다. 이제 기본 문법만 쓰다가 드디어 최신 문법을 적용하겠다면 꼭 배워두고 가야하는 것들이 있다.

Class
class를 사용할 때 function을 사용하지 않아도 된다. 

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Constructor (생성자)
constructor 메소드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메소드입니다.  "constructor" 라는 이름을 가진 특수한 메소드는 클래스 안에 한 개만 존재할 수 있습니다. 만약 클래스에 한 개를 초과하는 constructor 메소드를 포함한다면, SyntaxError 가 발생할 것입니다. 
constructor는 부모 클래스의 constructor 를 호출하기 위해 super 키워드를 사용할 수 있습니다.
extends를 사용하여 클래스를 상속받을 수 있습니다.
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.');
  }
}

메소드만을 포함할 수 있다. (변수를 선언하면 SyntaxError가 발생한다.)
=> 멤버변수의 초기화는 꼭 constructor안에서만 이루어지길.
또한, constructor는 언제나 public이다.

호이스팅이 되지 않기 때문에 class 선언 이후에 할당 받을 수 있다.

오버라이딩을 사용할 수 있다. (오버로딩을 지원하지 않는다.)

getter, setter 를 아래처럼 활용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Colored {
    initializer ()     { this._color = "white" }
    get color ()       { return this._color }
    set color (v)      { this._color = v }
}
 
class ZCoord {
    initializer ()     { this._z = 0 }
    get z ()           { return this._z }
    set z (v)          { this._z = v }
}
 
class Shape {
    constructor (x, y) { this._x = x; this._y = y }
    get x ()           { return this._x }
    set x (v)          { this._x = v }
    get y ()           { return this._y }
    set y (v)          { this._y = v }
}


ECMAScript6 - Class : http://poiemaweb.com/es6-class
ECMAScript 6 — New Features: Overview & Comparison : http://es6-features.org/#ClassDefinition

Pomise
비동기식 처리를 위한 패턴입니다.
비동기의 단점을 보완하며 비동기 시점을 명확하게 표현합니다.

Promise는 다음 중 하나의상태를 가집니다.
  • 대기중(pending): 초기 상태, 이행 또는 거부되지 않은.
  • 이행됨(fulfilled): 연산이 성공리에 완료되었음을 뜻합니다.
  • 거부됨(rejected): 연산이 실패했음을 뜻합니다.

메서드

Promise.all(iterable)
인수 iterable 내의 모든 프로미스가 결정된 때 결정되며 하나의 프로미스라도 거부된 경우 즉시 거부하는 프로미스를 반환합니다. 이 프로미스가 결정되는 경우, iterable 내의 프로미스가 결정한 값들의 배열로 결정됩니다. 반환된 프로미스가 거부되는 경우, iterable 내의 거부된 그 프로미스가 거부된 이유를 그대로 이용해 거부합니다. 이 메서드는 여러 프로미스의 결과를 모두 모으는 데 유용할 수 있습니다.
Promise.race(iterable)
iterable 내 프로미스 중 하나를 결정 또는 거부하자마자 결정 또는 거부하는 프로미스를 반환합니다, 그 프로미스로부터 값 또는 이유로.
Promise.reject(reason)
주어진 reason(이유)로 거부된 Promise 객체를 반환합니다.
Promise.resolve(value)
주어진 값(value)으로 결정된 Promise 객체를 반환합니다. 값이 thenable 객체인(즉 then 메서드가 있는) 경우, 반환된 프로미스는 그 thenable을 "따르고(follow)", 그 최종 상태를 취합니다; 그렇지 않으면 반환된 프로미스는 그 값으로 이행됩니다. 보통, 값이 프로미스인지 아닌지 알고 싶은 경우 - 대신 Promise.resolve(value)로 쓰고 프로미스처럼 반환값으로 작동합니다.

then, catch 를 사용하는 시점

1
2
3
4
5
6
7
8
9
10
11
12
13
// 프로미스가 then() 호출로 결정된/이행된 경우 무엇을 할 지를 정의하고,
    // catch() 메서드는 프로미스가 거부된 경우 무엇을 할 지를 정의합니다.
    p1.then(
        // 이행값 기록
        function(val) {
            log.insertAdjacentHTML('beforeend', val +
                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
        })
    .catch(
        // 거부 이유 기록
        function(reason) {
            console.log('Handle rejected promise ('+reason+') here.');
        });



1
2
3
4
5
6
7
8
9
10
11
12
13
function timeout(duration = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, duration);
    })
}
 
var p = timeout(1000).then(() => {
    return timeout(2000);
}).then(() => {
    throw new Error("hmm");
}).catch(err => {
    return Promise.all([timeout(100), timeout(200)]);
})



timeout에서 then과 catch를 사용하고 catch에서는 all이라는 메서드를 사용하여 다시 timeput을 걸었다.

ES6시대의 JavaScript : http://poiemaweb.com/es6-promise
(IE는 제외)

closure
외부함수 내의 변수를 필요로 하는 내부함수가 하나 이상 존재하는 경우에 있다가 이것이 소멸할 때를 클로저라고 한다.

init함수에 정의된 displayName함수가 사라지지 않고 다시 불려질 수 있는 것처럼 아직 클로저가 소멸하지 않은 것이다.
1
2
3
4
5
6
7
8
function init() {
    var name = "Mozilla"// name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

변수를 private하게 사용하기.
만약 privateCounter가 전역으로 선언되어 있었다면 어디서나 참조가 가능하겠지만,
그렇지 않고 함수 안에 선언되어 외부에서 함부로 참조할 수 없다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();
 
console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1

클로져의 성능을 고려하여
1
2
3
4
5
6
7
8
9
10
11
function MyObject(name, message) {
  this.name = name.toString();
  this.message = message.toString();
  this.getName = function() {
    return this.name;
  };
 
  this.getMessage = function() {
    return this.message;
  };
}

코드를 고친다. MyObject에서 getName, getMessage를 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
function MyObject(name, message) {
    this.name = name.toString();
    this.message = message.toString();
}
(function() {
    this.getName = function() {
        return this.name;
    };
    this.getMessage = function() {
        return this.message;
    };
}).call(MyObject.prototype);



Javascript Closure : http://poiemaweb.com/js-closure


'WEB 웹 > JAVASCRIPT' 카테고리의 다른 글

Magnific Popup  (0) 2017.12.01
gem - mustache  (0) 2017.11.30
Document (javascript30 - 13)  (0) 2017.11.23
Key Detection (javascript30 - 12)  (0) 2017.11.23
HTML Video Player (javascript30 - 11)  (0) 2017.11.22
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함