함수 메소드

이종원·2020년 10월 2일
0

함수를 실행하는 다양한 방법

  • function(method)호출
  • new키워드를 이용한 호출
  • 함수 메소드 .call .apply를 이용
function.prototype.apply()
function.prototype.bind()
function.prototype.call()

Method 호출
메소드 호출은 객체.메소드()과 같이 객체 내에 메소드를 호출하는 방법

Singleton 패턴
let counter = {
	vale: 0,
    increase: function(){
	  this.value++
},
	decrease: function(){
	  this.value-- 
},
	getValue: function(){
	  return this.vale
  }
}

counter1.increase()
counter1.increase()
counter1.increase()
counter1.decrease()
counter1.getValue() // 2

Singleton 패턴은 단 하나의 객체만 만들 수 있으므로 똑같은 기능을 하는 객체 여러개를 만드려면
클로저 모듈 패턴을 이용 또는 생성자 호출과 같이 사용가능

클로저 모듈패턴
function makeCounter(){
	return {
	value: 0
    increase: function(){
	  this.value++
},
	decrease: function(){
	  this.value--
},
	getValue: function(){
	  return this.value
   }
  }
}

let counter1 = makeCounter()
counter1.increase()
counter1.getValue() // 1

let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() // -2

call과 apply

<call, apply>

function add(x, y){
	this.val = x + y
    console.log(this.val)
}
let obj = { val: 0}

add.apply(obj, [2, 8]) //10
add.call(obj, 2, 8) // 10
차이는 대괄호 쓰고 안쓰고

.bind

  • call/apply와는 다르게 함수를 바로 실행하지 않고 this값이 바인딩 된 함수를 리턴
<bind>
function add(x, y){
	this.val = x + y
    console.log(this.val)
}
let obj = { val: 0}

let boundFn = add.bind(obj, 2, 8) // boundFn은 함수
boundFn() // 10 , 여기서 add가 실행됨

SetTimeout을 사용시 this값 전달

function Box(w, h){
    this.width = w
    this.height = h

    this.getArea = function() {
    return this.width * this.height
}

    this.printArea = function() {
    console.log(this.getArea())
}
}
let box1 = new Box(100, 50)
box1.printArea()
5000
setTimeout(box1.printArea, 4000) // 콘솔에서 함수에서 실행이 안되는걸 볼수있다
1
setTimeout(box1.printArea.bind(box1), 4000) // bind를 사용으로 실행이 된다
2
5000

bind로 인자 하나만 받는 커링 만들기

function func(name, money){
    return '<h1>' + name + '</h1><span>' + money + '</span>'
}
let funcSteve = func.bind(null, 'Steve') // 새로운 함수 만듬
funcSteve(1000) /// "<h1>Steve</h1><span>1000</span>" 인자 하나만 받음

let funbob = func.bind(null, 'bob')
funbob(10000) /// "<h1>bob</h1><span>10000</span>" 

0개의 댓글