'use strict';
// Never ever use the Arrow function as methods in the object
// Method must be a regular function, but inside of function in the method could be arrow function,
// because it inherits object, not the function
// Arrow function doesn't have the THIS keyword,
// so it simply uses THIS keyword from its srroundings, it's parent.
// Object doesn't have a scope - it is just literal, so the Window doesn't have object
var firstName = 'Matilda';
const hongsik = {
firstName: 'Hongsik',
year: 1988,
calcAge: function () {
console.log(this);
console.log(2037 - this.year);
// Solution 1
// const self = this; // this enables for isMillenial function to access this object
// // Because scope looking up
// const isMillenial = function () {
// // this keyword
// console.log(self); // it is outside of method
// console.log(self.year >= 1981 && self.year <= 1996);
// };
// Solution 2
const isMillenial = () => {
// this keyword
console.log(this); // it is outside of method
console.log(this.year >= 1981 && this.year <= 1996);
};
isMillenial();
},
// greet: () => console.log(`Hey, ${this.firstName}`),
greet: function () {
console.log(this);
console.log(`Hey, ${this.firstName}`);
},
};
hongsik.greet();
hongsik.calcAge();
// Arguments keyword
const addExpr = function (a, b) {
console.log(arguments);
return a + b;
};
addExpr(2, 5);
addExpr(2, 5, 8, 12); // Acceptable!
var addArrow = (a, b) => {
console.log(arguments);
a + b;
};
'Web > JavaScript' 카테고리의 다른 글
(JavaScript) Destructuring (0) | 2021.10.31 |
---|---|
(JavaScript) Primitives vs References types (0) | 2021.10.31 |
(JavaScript) THIS Keyword (0) | 2021.10.31 |
(JavaScript) Hoisting and TDZ (0) | 2021.10.31 |
(JavaScript) Hoisting (0) | 2021.10.31 |