2carrot84
by 2carrot84
1 min read

Categories

  • lecture

Tags

  • Closure
  • Node.js
  • Prototype

이번 수업에 들은 ‘Javascript 기초 이론’ 중 Closure 와 Prototype 에 대한 내용을 간략히 기입하고자 합니다.

Closure 는 몇번을 들어도 잘 이해가 안되는 개념 중에 하나죠.. 오늘은 이해를 할 수 있을지..😂

Javascript 기초 이론

Closure

Closure 는 function + environment 로 구성

  • function 이 하나 생길때 마다 closure 도 하나씩 생성
  • 함수 자신을 둘러싼 접근할 수 있는 모든 scope 가 environment
function and(x) {
    return function print(y) {
        return x + ' and ' + y
    }
}

const saltAnd = and('salt')
console.log(saltAnd('pepper'))  // salt and pepper
console.log(saltAnd('sugar'))   // salt and sugar

const waterAnd = and('water')
console.log((waterAnd('sugar')))    // water and sugar

위 코드에서 Closure 는?
function = print(y), environment = x -> ‘salt’

Closure 는 Higher-Order Function 을 만드는데 유용
Higher-Order Function 란? 하나 이상의 함수를 인자로 받거나, 함수를 결과로 반환 하는 function

function foo() {
    function bar() {}
    function baz() {}
}

foo()   // foo 1, bar 1, baz 1
foo()   // foo 1, bar 2, baz 2

Prototype

클래스 상속 개념으로 사용 되며, prototype chain 을 이용하게 된다.

// AS-IS
function Person(name) {
    this.name = name
}

Person.prototype.greet = function greet() {
    return 'Hi, ${this.name}!'
}

function Student(name) {
    this.__proto__.constructor(name)
}

Student.prototyp.study = function study() {
    return '${this.name} is studying'
}

Object.setPrototypeOf(Student.prototype, Person.prototype)
console.log([] instanceof Array, [] instanceof Object)
// TO-BE
class Person {
  constructor(name) {
    this.name = name
  }
  greet() {
    return 'Hi, ${this.name}!'
  }
}

class Student extends Person {
  constructor(name) {
    super(name)
  }
  study() {
    return '${this.name} is studing'
  }
}

const me = new Student('lee')
console.log(me.study()) // lee is studing
console.log(me.greet()) // Hi, lee!

마무리

어려운 개념인 만큼 수업을 들으면서 많은 메모를 하지 못 했네요..

수업이 끝나기전에 몇번 다시 돌려보면서 부족한 내용 기입하도록 하겠습니다.

그럼 이만. 🥕👋🏼🖐🏼