📁
til
  • TIL(Today I Learned)
  • javascript
    • value-number-string-boolean-null-undefined
    • primitive-reference
    • Hoisting
    • Prototypes in Javascript
    • this
    • prototype
    • 콜백함수 (Callback function)
    • 함수의 호출
    • 자료구조 new keyword
    • closure
    • Promise
    • event-loop
    • array-object
    • 객체
    • Arguments
    • higher order function
    • operators-function-control-flow
    • 객체 생성 패턴 3가지
    • Javascript scopes
    • Functional Programming
    • Design Patterns
    • 데이터 타입
    • Object 객체
    • 표준 내장 객체의 확장
    • 참조
    • 함수
    • 상속(Inheritance)
    • this - 'this'를 사용하는 해당 함수를 '어떻게' 실행하느냐에 따른 4가지 this 정의
    • 전역객체(Global object)
    • 객체 지향 프로그래밍
    • The 'new' keyword - Object Creation in JavaScript
  • javascript-api
    • Number
      • Number.MAX_VALUE
      • Number.isInteger
      • Number.NEGATIVE_INFINITY
      • Number.isNaN()
      • Number.POSITIVE_INFINITY
      • Number.parseFloat
      • Number.EPSILON
      • number.toExponential
      • Number.MAX_SAFE_INTEGER
      • Number1 - 자연수, 정수, 10진수, 2진수, 부동소수점, 실수
      • Number.isSafeInteger()
      • Number.MIN_VALUE
      • Number.parseInt
      • Number.NaN
      • Number.isFinite()
      • Number.MIN_SAFE_INTEGER
      • toFixed
    • string.split
    • String.fromCodePoint
    • string.trimEnd
    • string.padStart
    • string.@@iterator
    • String.fromCharCode
    • string.toUpperCase
    • string.codePointAt
    • string.toLowerCase()
    • string.toString
    • string.includes
    • string.replace()
    • string.charAt
    • String.lastIndexOf
    • string.slice
    • string.search
    • string.padEnd
    • string.substring
    • string.length
    • string.trim
    • string.localeCompare
    • String.indexOf
    • string.endsWith
    • string.valueOf
    • String.raw
    • string.matchAll()
    • string.repeat
    • string.match
    • String.prototype
    • string.startsWith
    • string.charCodeAt
    • string.trimStart
    • string.concat
    • string.toLocaleUpperCase()
    • string.toLocaleLowerCase
    • String
  • learn-node
    • debugger
    • Tip
  • schema-design
    • Database Schema Design
    • Database Schema Design
  • react
    • LifeCycle
    • redux
    • Context API
    • 함수형 컴포넌트와 클래스, 어떤 차이가 존재할까?
    • Hooks과 useEffect 사용해 보기
    • Route
    • async wait 사용하기
    • Hooks API Reference
    • context
    • npm uninstall 하는법
    • test 만들기
  • tip
    • 클린코드
    • BxSlider로 텍스트 흐르는 효과 만들기
  • javascript30
    • Event Capture, Propagation, Bubbling and Once
    • Object and Arrays - Reference VS Copy
  • typescript
    • 우아한 타입스크립트 2부
    • The Basic Cheatsheet
    • TypeScript
    • Type Guards and Differnetiating Types
    • 우아한 타입스크립트
    • Generics
  • git-from-the-hell
    • git
    • init-status-add-commit-log-stage-repository
    • log-diff
    • 머지 후 branch 삭제하기
    • 지옥에서 온 Git
    • reset-revert
    • develop branch 를 pull 하고 싶을때
  • conference-and-seminar
    • 모던 프론트엔드 개발환경의 이해
  • fire-base
    • Firebase .gitignore
  • vanillacoding
    • Data Structures
    • Sorting Algorithms - part 1
    • Promise
    • class
    • 04.quiz
    • 07.event-loop
    • Design Patterns
    • OOP (Object Oriented Programming)
  • etc
    • 알고리즘 코드리뷰
    • 스스로 공부하는 법
    • 바닐라코딩 수강 후기
    • async 과제 후기 - 비동기, 동기, 클로저, 배열과 객체
    • 유용한 사이트
  • algorithm
    • The Supermarket Queue
    • Find the odd int
    • The Office III - Broken Photocopier
    • Directions Reduction
    • The Office II - Boredom Score
    • Divisible Sum Pairs
    • Codewars 이용자 솔루션 모음
    • Shortest Word
    • find key
    • Two Sum
    • Simple Pig Latin
  • Book
    • the essence of object-orientation
      • 타입과 추상화
      • 객체 지도
      • 이상한 나라의 객체
      • 추상화 기법
      • 05. 책임과 메시지
      • 07.함께 모으기
      • 04. 역할, 책임, 협력
      • 협력하는 객체들의 공동체
  • ecma-script2015
    • Object Literal Upgrades
    • default-parameter-template-literals-arrow-functions
    • spread-operator-rest-param
    • let-const-rest-parameter-spread-operator-destructuring
  • http
    • 웹 브라우저에 URL을 입력했을 때 어떻게 웹 페이지가 보여질까?
  • jest
    • toThrow(error?)
  • data-structures
    • Data Structures
  • express
    • express generator
    • CORS
  • css-flexible-box-layout
    • flex 해버렸지 뭐야
  • git
    • Git
  • mongodb
    • MongoDB
  • markdown
    • use-markdown
  • cmder
    • cmd 명령어 모음
  • debug
    • trackClicksEx function error
  • npm
    • NPM TOKEN 설정하기
  • storybook
    • Storybook
  • sort
    • Sorting Algorithms - part 1
  • javascript-koans
    • Javascript Koans 오답노트
  • rxjs
    • Rx.js
  • dom-elements
    • HTML Element
  • redux-toolkit
    • Redux Toolkit
  • github-actions
    • GitHub Actions
  • redux-middleware
    • redux middleware
  • rest
    • rest
  • css-rendering
    • 코드 스피츠 - CSS Rendering 1회차 2/2
    • 코드 스피츠 - CSS Rendering 1회차 1/2
  • you-dont-know-js
    • 타입
  • server
    • # shutdown local server
  • semantic-versioning
    • Semantic Versioning 2.0.0
Powered by GitBook
On this page
  • apply
  • 호출한 함수의 this를 apply 첫번째 인자로 지정할 수 있다.
  • apply와 call의 차이는

Was this helpful?

  1. javascript

함수의 호출

함수도 객체(배열도 포함)다. 객체는 속성들을 가지고 있다.(프로퍼티, 메서드) 그래서 함수도 내장 메소드를 가지고 있다.

apply

function sum(arg1, arg2){
    return arg1+arg2;
} 
console.log(sum.apply(null, [1,2]));

apply 호출하는 역할을 한다. 간단한 예제를 보여주기 위해 이렇게 쓴거지만 첫번째 인자가 null을 쓰는경우 apply를 써야할 이유는 1도 없다.

호출한 함수의 this를 apply 첫번째 인자로 지정할 수 있다.

o1 = {val1:1, val2:2, val3:3};
o2 = {v1:10, v2:50, v3:100, v4:25};

function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}
console.log(sum.apply(o1)); // 6
console.log(sum.apply(o2)); //185

콘솔 부분을 다르게 설명하자면,

console.log(sum.apply(o1)); //이 부분은
console.log(o1.sum()); //이와같다고 할 수 있다

console.log(sum.apply(o2));
console.log(o2.sum());

코드 전체를 바꿔 설명해보면,

function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}

o1 = {val1:1, val2:2, val3:3, sum:sum};
o2 = {v1:10, v2:50, v3:100, v4:25, sum:sum};

console.log(o1.sum());
console.log(o2.sum());

이와 같다. 하지만,

// 첫번째 콘솔에 찍힌 값
6function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}
// 두번째 콘솔에 찍힌 값
185function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}

이렇게 쓰면 sum도 객체의 하나의 속성이 되어 숫자 6과 function이 같이 함쳐져서 나온다. 그래서 수정이 한번 더 필요하다.

function sum(){
    var _sum = 0;
    for(name in this){
        if(typeof this[name] !== 'function'){
            _sum += this[name];   
        }
    }
    return _sum;
}

o1 = {val1:1, val2:2, val3:3, sum:sum};
o2 = {v1:10, v2:50, v3:100, v4:25, sum:sum};

console.log(o1.sum());
console.log(o2.sum());

이렇게 직접 추가할 때는 객체에 굳이 함수를 추가해야하고 if문도 추가해야 한다. 이럴경우 apply가 적합하다.

apply와 call의 차이는

call는 두번째 인수에서 인수 목록을 받고 apply는 인수 배열 하나만 받는다.

Previous콜백함수 (Callback function)Next자료구조 new keyword

Last updated 5 years ago

Was this helpful?