Web/JavaScript
(JavaScript) THIS Keyword
haramang
2021. 10. 31. 13:52
'use strict';
console.log(this); // Window Object
const calcAge = function (birthYear) {
console.log(2037 - birthYear);
console.log(this);
};
calcAge(1991); // undefined
const calcAgeArrow = birthYear => {
// it doesn't have a this keyword
console.log(2037 - birthYear);
console.log(this);
};
calcAgeArrow(1988); // window
const hongsik = {
year: 1988,
calcAge: function () {
console.log(this);
console.log(2037 - this.year);
function calcAge2() {
console.log(this);
}
calcAge2(); // Undeifiend
},
};
hongsik.calcAge();
const matilda = {
year: 2017,
};
matilda.calcAge = hongsik.calcAge; // Method borrowing
matilda.calcAge();
const f = hongsik.calcAge;
// f(); // error - doesnt have year variable