Notice
Recent Posts
Recent Comments
Link
«   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
Tags
more
Archives
Today
Total
관리 메뉴

coding etude

200902 [Function method] 본문

Javascript TIL

200902 [Function method]

코코리니 2020. 9. 2. 22:35

Function method

 : 함수 내장 메소드// Function.prototype.method

 

@함수 실행 방법

  - function(method) 호출

  - new 생성자 호출

  - 함수 메소드 .call()/.appl() 를 사용하여호출

 

1. call 메소드

  : 생성 되어 있는 객체(함수 / 메소드)를 재할당 할때 사용하는 메소드로 인자로(this, argument) 로 주어진다

//예제1

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +
                      this.name + ' with a negative price');
  }
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

 

2. apply 메소드

  : call 과 동일한 기능을 하지만 들어오는 인자의 값을 Array  값으로 받는다.

// 배열 예제

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

※ 배열 number의 인자를 받아와서 메소드를 실행하여 단일 실행 값을 반환 한다.

 

3 유사배열(Array like object)

// 유사배열 예제
<body>
<div id="outer">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<script>
    let outer = document.querySelector('#outer').children;
  // console.log(outer)
 

console.log(outer) 

위의 예시처럼 html의 값을 script로 가져오면 length 와 index를 가지 배열의 형태를 가진다.

하지만 배열 메소드를 사용 할 수 없다. (filter, map, reduce ....)  

그래서 이럴 때 call, apply 와 같은 함수 메소드를 사용하여 배열 메소드를 사용 할 수 있다.

outer.push.call(this, div)

위의 예시처럼 배열 매소드의 사용이 가능해 진다.

 

4. bind 메소드

  : call , apply 와 동일한 기능으로 함수의 (this, argument)의 값을 가져오지만 call , apply는 함수를 실행한 값을 반환 한다면 bind는 함수 자체를 가져와서 반환하고 실행하지는 않는다

※ 유용한 예제로 onclick 이벤트예제가 있다.

 let users = [
      { name: kim },
      { name: pak },
      { name: lee }
    ]
    let result = []

    function userclick() {
      return {
        trigger: function () {
          this.onclick()
        }
      }
    }

    function handleClick() {
      result.push(this.name)
    }

    function callback(user) {
      let btn = createUserButton(user)
      btn.onclick = handleClick.bind(user) // bind 사용 예시
      btn.trigger()
    }

    users.forEach(callback)

위의 예시에서 bind를 사용하지 않았다면 함수가 바로 실행 되어 값이 바로 다 나오게된다. 하지만 bind 로 함수만 반환한 상태에서 클릭 이벤트가 있을 때, 클릭한  user 값을 전달 하기 때문에 클릭 이벤트가 성립된다.

 

 

5. this 

  : scope 역영에서 생성되는 방법의 따라서 지시하는 값이 달리지는 용어.

 

  @this 의 생성 패턴 

    1. global 참조

    2. 함수 호출

    3. call or apply 에 의한 호출

    4. 생성자 모드

    5. 메소드 호출

1번 과 2번은 global/window 를 참조하는 this 이지만 3~5번 까지는 생성되는 방법에 따라서 가리키는 값이 다르다.

  추후 this 만 다룰 때 상세하게 성명 하겠다.

 

 

'Javascript TIL' 카테고리의 다른 글

200904 [ESlint]  (0) 2020.09.06
200903 [Prep]  (0) 2020.09.05
200831 [github 활용하기]  (0) 2020.08.31
200830 [고차함수]  (0) 2020.08.31
200828 [DOM]  (0) 2020.08.29