THIS.OBJECT
console.log(this);
//printed
//Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}
calculateAge(1985);
function calculateAge(year){
console.log(2016-year);
console.log(this);// 'this' printed window things here
}
//in the regular function call "this" is always pointing to window.
var john = {
name: "John",
yearOfBirth: 1990,
calculateAge: function() {
console.log(this);
//printed attached object // {name: "John", yearOfBirth: 1990, calculateAge: ƒ}
console.log(2016-this.yearOfBirth); //26
/*
function innerFunction(){
console.log(this);
// printed window {...} obj
// it is inside of obj, but it's still function!!!!!!!!
}
innerFunction();
*/
}
}
john.calculateAge();
//only in method, it is pointed to the object
var mike = {
name: "Mike",
yearOfBirth: 1984
};
mike.calculateAge = john.calculateAge;
// It was john's "this", but after "mike" called the method it is changed to "mike's".
//->'this' keyword become a something after the method get called
mike.calculateAge();
THIS.VARIABLE
- in regular function call : points at the global object(window object, in the browser).
- method call : points to the object that called the method.
"this" is not assingned any value until the function that it is in is actually called.
:this 키워드는 펑션이 호출되기 전 까지는 아무 의미 없다.
'javascript' 카테고리의 다른 글
JavaScript/ Primitives vs Objects (0) | 2020.02.24 |
---|---|
JavaScript/ Function constructor (0) | 2020.02.24 |
JavaScript/ Scoping/ 변수영역 (0) | 2020.02.24 |
JavaScript/ Hoisting, Function and Variable (0) | 2020.02.14 |
JavaScript/ Loops and Iteration (0) | 2020.02.13 |