Kim-Baek 개발자 이야기

Javascript Call, This 본문

개발/JavaScript

Javascript Call, This

킴백 개발자 2020. 10. 4. 18:50

함수 호출과 this

 

Arguments 객체

 

  • 자바스크립트에서 함수를 호출할 때 인수들과 함께 암묵적으로 arguments 객체가 함수내부로 전달된다.

 

  • arguments 객체는 유사 배열 객체이다

 

  • 넘겨진 인자(배열), length, callee(함수의 참조 값) 으로 구성되어 있다.
 function sum(a, b){
   return a+b;
 }
 console.log(sum(1));     //NaN
 console.log(sum(1,2));   //3
 console.log(sum(1,2,3)); //3

  // length를 이용한 구현
  function sum(){
    var result = 0;
    for(var i=0; i < arguments.length; i++){
      result += arguments[i];
    }
    return result;
  }
  console.log(sum(1,2,3,4,5,6,7,8,9,10)); //55

 

 

호출 패턴과 this 바인딩

  • 자바스크립트에서 함수를 호출할 때 기존 매개변수로 전달되는 인자값에 뿐만 아니라 arguments 객체와 this 인자가 함수 내부로 전달된다.

 

객체의 메서드 호출할 때 this 바인딩

 

  • 객체의 프로퍼티가 함수일 경우, 메서드 내부 코드에서 사용된 this는 해당 메서드를 호출한 객체로 바인딩된다.

 

 var obj = {
    name: 'foo',
    hello: function() {
      console.log(this.name);
    }
  }
  var obj2 = {
    name: 'bar';
  }
  obj2.hello = obj.hello;

  obj.hello();  //foo
  obj2.hello(); //bar

 

함수를 호출할 때 this 바인딩

 

  • 함수를 호출하면, 해당 함수 내부 코드에서 사용된 this는 전역 객체(window 객체)에 바인딩된다.

 

 var value = 100; //window 객체의 변수
 var obj = {
   value: 1,
   func1: function(){
     this.value += 1;
     console.log(this.value);

     func2 = function(){
       this.value += 1;
       console.log(this.value);

       func3 = function(){
         this.value += 1;
         console.log(this.value);
       }

       func3();
     }
     func2();
   }
 };
 obj.func1();

> 결과 값은 2, 101, 102 이다. func1의 this는 obj가 호출 했기때문에 obj에 바인딩된다. func2와 func3은 호출한 객체가 없기 때문에 window객체에 바인딩된다.

 

생성자 함수를 호출할 때 this 바인딩

 

  • 기존 함수에 new 연산자를 붙여서 호출하면 해당 함수는 생성자 함수로 동작한다.

 

  • 생성자 함수를 호출하면 생성자 함수는 빈 객체(생성자 함수의 prototype 프로퍼티를 가리킴)가 만들어 지고, 이 빈 객체에 this로 바인딩된다.

 

 var Person = function(name, age){
   this.name = name;
   this.age = age;
 }
 var foo = new Person('foo', 26);
 console.log(foo.name, foo.age); //foo,26

자바의 this처럼 생성자 함수로 만들어진 빈 객체가 this에 바인딩 된다.

 

참고로 생성자 함수로 만들어진 객체는 생성자 함수의 prototype 프로퍼티가 가리키는 객체를 자신의 프로토타입 객체로 설정한다.

 

객체 리터럴 방식으로 만들어진 객체는 자신의 프로토타입 객체가 Object 객체이다.

 

 

call과 apply 메소드를 이용한 명시적인 this 바인딩

 

function Person(name, age){
   this.name = name;
   this.age = age;
 }
 var foo ={};
 var bar ={};
 Person.apply(foo, ['foo', 26]);
 Person.apply(bar, 'bar', 26);

 

 //arguments 객체를 배열로 만들기
 function myFunc(){
   var args = Array.prototype.slice.apply(arguments);
   return args;
 }
반응형
Comments