본문 바로가기

Programming/JavaScript

Object Methods

const sunny = {
    firstName: 'Sunny',
    lastName: 'Ryu',
    birthYear: 1988,
    job: 'technical writer',
    hobbies: ['Writing', 'Coding', 'Learning'],
    hasDriversLicense: true,

    calcAge: function (birthYear) {
        return 2022 - birthYear;
    }
};

console.log(sunny.calcAge(1988)); // prints 34
console.log(sunny['calcAge'](1988)); // prints 34

 

Don't repeat by yourself principle

위에서 보면 birthYear 1988을 2번 이상 반복해서 사용함

근데 그러면 human error로 정확하지 않게 입력하지 않는 곳도 발생할 수 있음

& 애초에 코딩할 때 이렇게 반복되는 값을 manually 써주는게 좋은 습관 아님 🙅‍♀️

 

그럼 how? This keyword를 사용함

this는 object 자체를 가리킴

해당 object의 birthYear에는 이미 1988이라는 값이 담겨있으니-

this.birthYear를 호출하면 된다!

    calcAge: function () {
        console.log(this);
        return 2022 - this.birthYear;
    } // prints 34

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

 

 

JavaScript this

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

    calcAge: function () {
        this.age = 2022 - this.birthYear;
        return this.age;
    } // prints 34

console.log(sunny.calcAge()); // prints 34

 

Tried

    calcAge: function () {
        this.age = 2022 - this.birthYear;
        return this.age;
    },

    isSheAbleToDrive: function () {
        this.driversLicense = this.hasDriversLicense ? 'a' : 'no';
        return this.driversLicense
    }
};

console.log(`Sunny is a ${sunny.calcAge()}-year old technical writer, and she has ${sunny.isSheAbleToDrive()} driver's license`);

와... 뻘짓 2가지 했는데

1. 함수 연달아 올때 caclAge 중괄호(curly brace) 뒤에 , 컴마 찍어줘야 함

2. 함수 호출할 때 () 소괄호(brace) 빠뜨리지 말기!

 

Answer

    getSummary: function () {
        return `${this.firstName} is a ${this.calcAge()}-year old ${sunny.job}, and she has ${this.hasDriversLicense ? 'a' : 'no'} driver's license.`
    }
    
    console.log(sunny.getSummary());

'Programming > JavaScript' 카테고리의 다른 글

Iteration: The for Loop  (0) 2022.09.15
Coding Challenge #3 - comparing BMIs using objects  (0) 2022.09.15
Dot vs. Bracket Notation  (0) 2022.09.11
Introduction to Objects  (0) 2022.09.11
Coding Challenge #2 - tip calculator with arrays  (0) 2022.09.10