[JS] Object (feat. ꡬ식 prototype 버전)

ChenΒ·2024λ…„ 6μ›” 12일

Javascript

λͺ©λ‘ 보기
11/22
post-thumbnail

객체

const person = {};
// 속성, property
person.name = '일뢄이';
person.age = 10;
// λ©”μ†Œλ“œ, method
person.introduce = function () {
    console.log('μ•ˆλ…•ν•˜μ„Έμš”. μ €λŠ” 일뢄이이고 λ‚˜μ΄λŠ” 10μ‚΄μ΄μ—μš”');
};
person.introduce();
const perseon = {
    name: '일뢄이',
    age: 10,
    introduce: function () {
        console.log('μ•ˆλ…•ν•˜μ„Έμš” μ €λŠ” 일뢄이이고, λ‚˜μ΄λŠ” 10μ‚΄μ΄μ—μš”');
    },
};
const person = {
    name: '일뢄이',
    age: 10,
    introduce: function () {
        console.log(`μ•ˆλ…•ν•˜μ„Έμš” μ €λŠ” ${this.name}이고, λ‚˜μ΄λŠ” ${this.age}μ‚΄μ΄μ—μš”`);
    },
};

1. μƒμ„±μž ν•¨μˆ˜ 방식

μ§€κΈˆ ECMA Script μ—μ„œλŠ” class 문법이 μΆ”κ°€λμŒ. 이건 μ˜›λ‚  버전!

  • μƒμ„±μž ν•¨μˆ˜ ν˜ΈμΆœμ„ ν•  λ•Œ ν•¨μˆ˜κ°€ μƒμ„±μžλ‘œμ„œ 호좜이 되게 ν•˜κ³  μ‹ΆμœΌλ©΄ new 뢙이면 됨. κ·Έλž˜μ„œ 각각 κ°œλ³„ 객체λ₯Ό thisκ°€ κ°€λ¦¬ν‚€κ²Œ 된 것

μΈμŠ€ν„΄μŠ€

= 각각의 μƒμ„±μž ν•¨μˆ˜λ‘œ λ§Œλ“€μ–΄λ‚Έ 객체

/// μƒμ„±μž (constructor)
function Person(nickname, age) {
    this.nickname = nickname;
    this.age = age;
    this.introduce = function () {
        console.log(`μ•ˆλ…•ν•˜μ„Έμš” μ €λŠ” ${this.nickname}이고, λ‚˜μ΄λŠ” ${this.age}μ΄μ—μš”`);
    };
}
// μΈμŠ€ν„΄μŠ€ (instance)
const person1 = new Person('일뢄이', 10);
const person2 = new Person('이뢄이', 8);

person1.introduce();
person2.introduce();

🀍 κ°œμ„  => κ³΅μœ ν•˜λŠ” 속성/λ©”μ†Œλ“œλŠ” prototype 객체에 μ •μ˜ν•˜κΈ°

introduce도 this.nickname, this.age와 같이 같은 λ ˆλ²¨μ— 있기 λ•Œλ¬Έμ— λ©”λͺ¨λ¦¬ 점유. ν•˜μ§€λ§Œ introduceλŠ” λ‹€ λ˜‘κ°™μ€ prop. κ·Έλž˜μ„œ λΉ„νš¨μœ¨μ . λ©”λͺ¨λ¦¬ λ‚­λΉ„μž„

=> ν•˜λ‚˜λ§Œ λ§Œλ“€μ–΄λ†“κ³  κ°œλ³„ 객체듀이 κ³΅μœ ν•˜κ²Œλ”

function Card(num, color) {
    this.num = num;
    this.color = color;
}

Card.prototype.width = 100;
Card.prototype.height = 150;

const card1 = new Card(1, 'green');
const card2 = new Card(2, 'red');

console.log(card1.color);
console.log(card2.color);
console.log(card1.width);
console.log(card2.width);

function Card(num, color) {
    this.num = num;
    this.color = color;
    this.init();
}

Card.prototype = {
    constructor: Card,
    init: function () {
        const mainElm = document.createElement('div');
        mainElm.style.color = this.color;
        mainElm.innerHTML = this.num;
        mainElm.classList.add('card');
        document.body.appendChild(mainElm);
    },
};

const card1 = new Card(1, 'green');
const card2 = new Card(2, 'red');

2. class 방식

class Card {
    constructor(num, color) {
        this.num = num;
        this.color = color;
        this.init();
    }

    init() {
        const mainElm = document.createElement('div');
        mainElm.style.color = this.color;
        mainElm.innerHTML = this.num;
        mainElm.classList.add('card');
        document.body.appendChild(mainElm);
    }
}

const card1 = new Card(1, 'green');
const card2 = new Card(2, 'red');

profile
ν˜„μ‹€μ μΈ λͺ½μƒκ°€

0개의 λŒ“κΈ€