코락 CoRock
코딩하는 락스타
코락 CoRock
  • 분류 전체보기 (393)
    • frameworks (19)
      • spring (19)
      • spring-boot (0)
      • testing (0)
    • languages (94)
      • java (39)
      • kotlin (0)
      • python (42)
      • r (13)
    • libraries (0)
    • programming (239)
      • android (13)
      • c (17)
      • cpp (22)
      • database (18)
      • design-pattern (4)
      • data-structures (11)
      • git (8)
      • hadoop (6)
      • html-css (7)
      • issue (4)
      • javascript (26)
      • jsp (34)
      • os (29)
      • php (6)
      • preferences (19)
      • etc (15)
    • discography (37)
      • k-pop (18)
      • pop (19)
    • blog (3)

블로그 메뉴

  • Programming
  • Java
  • JavaScript
  • Discography
  • K-Pop Songs
  • Pop Songs
  • Blog
  • Guestbook

공지사항

인기 글

태그

  • Java
  • Android
  • oracle
  • CentOS
  • python
  • linux
  • javascript
  • r
  • 파이썬
  • 자바스크립트
  • Spring
  • jsp

최근 댓글

최근 글

티스토리

반응형
hELLO · Designed By 정상우.
코락 CoRock

코딩하는 락스타

[33-js-concepts] 15. this, call, apply and bind
programming/javascript

[33-js-concepts] 15. this, call, apply and bind

2020. 2. 17. 20:34
반응형

this

 : 함수나 메서드를  호출하는 주체 ( 함수의 실행영역)

 

  - call, apply, bind

  : 함수의 실행영역을 지정

 

 함수의 호출 방식

 1.  함수이름();

 2. 함수이름.call / apply / bind ( 인자) 

 

1의 방식이 기본적인 방식이며 함수의 호출 형태에 따라 this 가 변화!

 

(예시)

var obj = {
	a: 2,
	foo: foo
};
var bar = obj.foo;
var a = "나는야 전역";
bar();
function doFoo(fn) {
	fn();
}
var obj = {
	a: 2,
	foo: foo
};
var a = "나는야 전역";
doFoo(obj.foo);

 

 

2의 방식은 전달받은 인자가 this로 지정!

 

** 차이점 (요약)

  [call, apply ] : 함수를 호출하여 실행합니다.

   - call : 다수의 인자

   - apply : 단일 배열 인자

  [bind] : 새로운 함수를 생성한다

 

 

 call 

[ 함수의 생성자에 연결 ]

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';
console.log(this);
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
console.info(cheese);
// Food {name: "feta", price: 5, category: "food"}
console.info(fun);
// Toy {name: "robot", price: 40, category: "toy"}


[ 익명의 함수에 연결 ]

var sData = 'Wisen';            

function display(){
  console.log('sData value is %s ', this.sData);
}

display.call();  // sData value is Wisen

 

 apply 

[배열과 배열을 붙이기]

 - array.push의 경우,  배열을 단일 요소로 취급.

  - array.push.apply 을 이용하면, 배열이 아닌 배열내의 요소들을 취급

 ++ array.concat 의 경우, 해당 배열들이 모두 보존된 상태에서 새로운 배열을 생성하는 것임으로 최적화 x

var array = ['a', ‘b’];

var elements = [0, 1, 2];
array.push(elements); 
console.info(array); // ["a", "b", Array(3)]
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

 

[내장함수와 함께 이용]

// min/max number in an array

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

// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
console.info(max) // 7

 

 

 bind 

  :  새로운 함수를 생성.

 

 

   ** 지정함수.bind()가 실행되면, 리턴 값으로 새로운 함수가 생성되어 옵니다.

       새로 생성된 함수는 지정함수객체를 감싸서 만들어진 함수입니다.

      생성된 함수를 호출하게 되면, 지정된 this값을 전달하여, 항상 동일한 this값을 가지게 됩니다.

this.x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX();
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81

 

     

** 혹은 this지정과 함께 초기인수값을 지정할 수도 있습니다.

function addArguments(arg1, arg2) {
    return arg1 + arg2
}

var result1 = addArguments(1, 2); // 3

// 첫 번째 인수를 지정하여 함수를 생성합니다.
var addThirtySeven = addArguments.bind(null, 37); 

var result2 = addThirtySeven(5); // 37 + 5 = 42 

// 두 번째 인수는 무시됩니다.
var result3 = addThirtySeven(5, 10); // 37 + 5 = 42
반응형
저작자표시 비영리 변경금지 (새창열림)
    'programming/javascript' 카테고리의 다른 글
    • [33-js-concepts] 18. Object.create and Object.assign
    • [33-js-concepts] 16. new, 생성자, instanced, 인스턴스 (new, Constructor, instanced and Instances)
    • [33-js-concepts] 14. 팩토리와 클래스 (Factories and Classes)
    • [33-js-concepts] 13. DOM과 Layout Trees (DOM and Layout Trees)
    코락 CoRock
    코락 CoRock
    A COder dreaming of being a ROCKstar

    티스토리툴바