this
# 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