ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (loading)this
    Javascript 2020. 4. 15. 17:25

     

    this

    this 키워드는 어떠한 객체를 가르킵니다.

    객체를 가르키는 기준을 무엇일까요?

     

    5 Patterns of Binding 'this' 

     

    Global scope

    Function Invocation

    Method Invocation

    Construction mode

    [call, apply, bind]

     

     

    Global scope: window

     

    function 호출: window

    //Global & function invocation
    var name = 'Global Variable';	// === window.name
    console.log(this.name);
    
    function foo() {
      console.log(this.name);	// this === window
    }
    foo();
    
    function outer() {
      function inner() {
        console.log(this.name);	//this === window
      }
      inner();
    }
    outer();
    
    function outer2() {
      var closure = function() {
        console.log(this.name)
      }
      return closure;
    }
    outer2()();
    

     

    method 호출: 부모 object

    Method invocation
    var counter = {
      val: 0,
      increment: function() {
        this.val += 1;		//this === counter(부모)
      }
    };
    
    counter.increment();
    console.log(counter.val);  // 1
    counter['increment']();
    console.log(counter.val);  // 2
    
    let obj2 = {
      hello: {
        fn: function() { console.log(this); }
      },
      foo: function() { console.log(this); }
    }
    
    obj2.hello.fn()  //{fn: f}
    obj2.foo();  //{hello: {...}, foo: f}
    
    
    var obj = {
      fn: function(a,b) {
        return this
      }
    };
    var obj2 = {
      method: obj.fn
    };
    
    console.log(obj.fn() === obj)	//true
    console.log(obj2.method() === obj2)	//true
    
    
    //추가로 function invocation의 this가 window인 이유는 부모이기 때문이다.
    function foo() {
      console.log(this);
    }
    console.log(foo() === window.foo())	//true

     

    construction mode (new 연산자로 생성된 function 영역의 this): 새로 생성된 객체

    function F(v) {
      this.val = v;
    }
    
    var f = new F('WooHoo!');
    
    console.log(f.val);  //WooHoo!
    console.log(val);	//ReferenceError

     

     

     

    .call or .apply 호출: call. apply의 첫번째 인자로 명시된 객체

     

    function identify() {
      return this.name.toUpperCase();
    }
    function speak() {
      var greeting = "Hello, I'm " + identify.call(this);
      console.log(greeting)
    }
    var me = { name: "Kyle" };
    var you = { name: "Reader" };
    
    identify.call( me );	// KYLE
    identify.call( you );	// READER
    speak.call( me );	// Hello, I'm KYLE
    speak.call( you );	// Hello, I'm READER
    
    //call과 apply의 차이
    var add = function (x, y) {
     this.val = x, y;
    }
    var obj = {
      val: 0
    };
    
    add.apply(obj, [2, 8]);	// 첫번째는 this, 파라미터를 배열로 넘겨준다.
    console.log(obj.val);	// 10
    add.call(obj, 2, 8);	// 첫번째는 this, 파라미터를 쉼표로 넘겨준다.
    console.log(obj,val);	// 10
    //함수에 this를 안쓰고 있을 경우
    function add(x, y) {
      return x + y;
    }
    
    add.call(null, 2, 8)
    add.apply(null, [2, 8])
    //apply를 쓰는 이유
    Math.max(1,2,3,100,6,7)		// 100
    
    //만약에 배열로 주어지는 경우
    let arr = [1,2,3,100,6,7]
    Math.max.apply(null, arr)	// 100
    

     

     

     

     

    정리

    this	// global reference
    
    function bar() {
     console.log(this)
    }
    
    bar()	//function invocation
    window.bar()	//method invocation
    var barInstance = new bar();	//construction mode
    bar.call({a: 1})	//call, apply

     

     

     

    arrow function

    'Javascript' 카테고리의 다른 글

    package.json  (0) 2020.04.27
    Runtime & Node.js  (0) 2020.04.27
    미정의 매개변수를 배열로 받는 나머지 매개변수 (Rest parameter)  (0) 2020.04.12
    클로저 (Closure)  (0) 2020.04.02
    데이터 타입 (data type)  (0) 2020.04.02

    댓글

Designed by CHANUL