'this' keyword
5 Patterns of binding 'this'
1. global: window
2. Function 호출 : window
<global: window , Function 호출 : window>
var hello = 'world'
function foo(){
console.log(this.helle)
}
this.hello // 'world'
foo() // 'world'
결론 this는 window
<Method 호출 : 부모 object>
let obj = {
foo : function(){ console.log(this) }
}
obj.foo() // {foo: f} 부모 object
<Construction mode>
function F(v){
this.val = v
}
let f = new F('WooHoo')
console.log(f.val) // WooHoo
console.log(val) // ReferenceError
<.call, or apply 호출>
function bar(){
console.log(this)
}
bar.call(obj) // obj
bar.call({a : 1}) // {a : 1} 즉 this 값이 변함
--------------------------------------------
let add = function(x, y){
this.val = x + y
}
let obj = {
val: 0
}
add.apply(obj, [2,8])
console.log(obj.val) // 10
add.call(obj, 2,8)
console.log(obj.val) // 10
this는 함수 실행시 호출 방법에 의해 결정되는 특별한 객체이다
함수 실행시 결정되므로 실행되는 맥락에 따라 this는 다르게 결정됩니다
함수 실행의 다섯가지 방법
1.global : 정확히 말하면 함수 실행은 아니고 전역에서 this를 참조 할 때를 의미함
console.log(this)
2.function 호출
foo()
3.method 호출
obj.foo()
4.new 키워드를 이용한 생성자 호출
new Foo()
5.call 또는 .apply 호출
foo.call()
foo.apply()