November 21, 2019
어떤 함수가 호출되면, 실행 컨텍스트(execution context)가 만들어진다.
여기에 담긴 것
this
keywordthis
Function 호출 : window
var name = 'Global Variable';
// case1
console.log(this.name); // Global Variable
// case2
function foo() {
console.log(this.name);
}
foo(); // Global Variable
// case3
function outer() {
function inner() {
console.log(this.name);
}
inner();
}
outer(); // Global Variable
// case 1
let counter = {
val : 0,
increment : function() {
this.val ++;
}
}
counter.increment();
counter.val // 1
// case 2
let obj = {
fn : function(a, b) {
return this;
}
}
let obj2 = {
method : obj.fn
}
console.log(obj.fn() === obj) // true
console.log(obj2.method() === obj2) // true
// 함수를 실행시킨 대상이 this가 된다
function Food(name) {
this.name = name;
}
let food1 = new Food('지코바');
food1.name // "지코바"
// case1
function identify() {
return this.name.toUpperCase();
}
function speak() {
let greeting = "Hello, I'm " + identify.call(this);
console.log(greeting);
}
let me = {name : 'Heaeun'};
let you = {name : 'Daeun'};
identify.call(me); // "HEAEUN"
identify.call(you); // "DAEUN"
speak.call(me); // Hello, I'm HEAEUN
speak.call(you); // Hello, I'm DAEUN
let fn = function (one, two) {
console.log(this, one, two);
};
let r = {r:1};
let g = {g:1};
let b = {b:1};
let y = {y:1};
r.method = fn;
r.method(g, b); // this : r
fn(g, b); // this : window
fn.call(r, g, b) // this : r
r.method.call(y, g, b) // this : y