Part. 12 this

Angelo·2020년 5월 6일
0

Codestates PRE Javascript

목록 보기
12/15
post-thumbnail

greenday-Last Night on Earth

this

  • 모든 함수 scope 내에서 자동으로 설정되는 특수한 식별자
  • execution context의 구성 요소 중 하나로, 함수가 실행되는 동안 이용할 수 있다
  • 5 paterns of binding 'this'
  1. Global : window
  2. Function 호출 : window
  3. Method 호출 : 부모 object
  4. Construction mode (new 연산자로 생성된 function 영역의 this) : 새로 생성된 객체
  5. .call or .apply 호출 : call, apply의 첫번째 인자로 명시 된 객체
# Global & function invocation 
// .this 는 window 
var name = 'Global Variable';
console.log(this.name); // "Global Variable"

function foo () {
  console.log(this.name); // "Global Variable"
}

foo();

--

var name = 'Global Variable';

function outer () {
  function inner () {
    console.log(this.name); // "Global Variable"
  }
  
  inner();
}
outer();

-- 

var name = "Global Variable';

function outer2() {
  var closure = function() {
    console.log(this.name); // "Global Variable"
  }
  return closure;
}
outer2()();

-- 

# Method 호출 : 부모 Object
// this는 counter object
var counter = {
  val : 0;
  increment : function () {
    this.val + = 1;
  } 
};
counter.increment();
console.log(counter.val); // 1

counter['increment']();
console.log(counter.val); //2

-- 

var obj = {
  fn : function (a,b) {
    return this;
  }
};
var obj2 = {
  method : obj.fn
};
console.log (obj2.method() === obj2);
console.log (obj.fn() === obj);
// true, true 

-- 

# Construction Mode 
(new 연산자로 생성된 function 영역의 this):새로 생성된 객체 
// this는 f
function F (v) {
  this.val = v;
} // create new instance of F
var f = new F ('WooHoo!');

console.log (f.val) ; // WooHoo!
console.log (val); // ReferenceError

--

# call or .apply Invocation 
(call, apply의 첫번째 인자로 명시된 객체)
//this가 me or you
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

--

var add = function (x,y) {
  this.val = x + y ; 
}
var obj = {
  val : 0
};

add.apply (obj, [2, 8]);		//this는 obj
console.log(obj.val); // 10

add.call (obj, 2, 8);		//this는 obj
console.log(obj.val); // 10
profile
나만의 학습 노트

0개의 댓글