2016년 9월 22일 목요일

커스텀 이벤트, 상속

util.inherits(constructor, superConstructor)#

Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.
As an additional convenience, superConstructor will be accessible through the constructor.super_ property.
const util = require('util');
const EventEmitter = require('events');

function MyStream() {
    EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
    this.emit('data', data);
}

var stream = new MyStream();

console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true

stream.on('data', (data) => {
  console.log(`Received data: "${data}"`);
})
stream.write('It works!'); // Received data: "It works!"


비동기식 함수 구현과 사용


  • 비동기식 함수 구현

function addNum(num1, num2, callback) {
var res = num1 + num2;
callback(res);
}

  • 비동기식 함수 사용

addNum(9, 23, function(res) {
alert('addNum Result : ' + res);
});
비동기식으로 동작하는 함수는 반환(return)을 이용해서 결과를 전달하지 않고 콜백(callback) 함수를 이용한다. 비동기 동작을 모두 마치면 callback 함수가 동작하면서, 그 결과가 콜백 함수의 파라미터로 전달된다.
* 비동기 코드를 사용할 때는, 동작의 결과를 콜백 함수의 파라미터로 입력한다.