μλ°μ€ν¬λ¦½νΈμ κ°μ²΄λ μ΄λ¦κ³Ό κ°μ ν μμΌλ‘ λ¬Άμ μ§ν©μ΄λ€. ν μμ μ΄λ£¬ κ²μ νλ‘νΌν°
κ·Έκ²μ μ΄λ¦μ ν€(key)
λΌκ³ νλ€. κ°μΌλ‘λ λͺ¨λ λ°μ΄ν° νμ
μ λ°μ΄ν°λ₯Ό μ μ₯ν μ μλ€.
κ°μ²΄λ₯Ό μμ±νλ λ°©λ²μλ λ€μ μΈκ°μ§κ° μλ€.
1. κ°μ²΄ 리ν°λ΄λ‘ μμ±νλ λ°©λ²
var card = { suit: "ννΈ", rank: "A" };
2. μμ±μλ‘ μμ±νλ λ°©λ²
function Card(suit, rank) {
this.suit = suit;
this.rank = rank;
}
var card = new Card("ννΈ", "A");
console.log(card); // Card { suit: 'ννΈ', rank: 'A' }
3. Object.createλ‘ μμ±νλ λ°©λ²
var card = Object.create(Object.prototype, {
suit: {
value: "ννΈ",
writable: true,
enumerable: true,
configurable: true,
},
rank: {
value: "A",
writable: true,
enumerable: true,
configurable: true,
},
});
console.log(card); // Card { suit: 'ννΈ', rank: 'A' }
μμ±μ μμμ λ©μλλ₯Ό μ μν λ λ¬Έμ μ
μμ±μ μμμ this λ€μ λ©μλλ₯Ό μ μνλ©΄ λͺ¨λ μΈμ€ν΄μ€μ λκ°μ λ©μλκ° μΆκ°λλ€. λ°λΌμ κ°μ μμ
μ νλ λ©μλλ₯Ό μΈμ€ν΄μ€ κ°μλ§νΌ μμ±νκ² λλ©° κ·Έλ§νΌμ λ©λͺ¨λ¦¬λ₯Ό μλΉνκ² λλ€.
function Circle(center, radius) {
this.center = center;
this.radius = radius;
this.area = function () {
return Math.PI * this.radius * this.radius;
};
}
// κ°κ°μ μΈμ€ν΄μ€κ° λκ°μ λ©μλ areaλ₯Ό μμ νλ€.
var c1 = new Circle({ x: 0, y: 0 }, 2.0);
var c2 = new Circle({ x: 0, y: 1 }, 3.0);
var c3 = new Circle({ x: 1, y: 0 }, 1.0);
μ΄λ¬ν λ¬Έμ λ νλ‘ν νμ
κ°μ²΄μ λ©μλλ₯Ό μ μνλ λ°©μμΌλ‘ ν΄κ²° ν μ μλ€.
νλ‘ν νμ
κ°μ²΄
JSλ ν¨μλ κ°μ²΄μ΄κΈ° λλ¬Έμ κΈ°λ³Έμ μΌλ‘ prototype
νλ‘νΌν°λ₯Ό κ°κ³ μλ€.
ν¨μμ prototype νλ‘νΌν°κ° κ°λ¦¬ν€λ κ°μ²΄λ₯Ό κ·Έ ν¨μμ νλ‘ν νμ
κ°μ²΄λΌκ³ νλ€. κΈ°λ³Έμ μΌλ‘ λΉ κ°μ²΄λ₯Ό κ°λ¦¬ν΄
function F() {}
console.log(F.prototype); // Object {}
νλ‘ν νμ κ°μ²΄μ νλ‘νΌν°λ μμ±μλ‘ μμ±ν λͺ¨λ μΈμ€ν΄μ€μμ κ·Έ μΈμ€ν΄μ€μ νλ‘νΌν°μ²λΌ μ¬μ©
F.prototype.prop = "value";
var obj = new F();
console.log(obj.prop); // value
μΈμ€ν΄μ€μ νλ‘νΌν°μ κ°μ λμ νμ λ μ΄λ¦μ΄ κ°μ νλ‘νΌν°κ° μμΌλ©΄ κ·Έ νλ‘νΌν°μ κ°μ λμ νλ€.
obj.prop = "instance value";
console.log(obj.prop); // instance value
console.log(F.prototype.prop); // prototype value
νλ‘ν νμ
κ°μ²΄μ νλ‘νΌν°λ₯Ό μΈμ€ν΄μ€μμ μ°Έμ‘°ν μ μλ μν©μ κ°λ¦¬μΌ μΈμ€ν΄μ€κ° νλ‘ν νμ
κ°μ²΄λ₯Ό μμνκ³ μλ€
λΌκ³ νλ€. μμμ μΈκΈν μμ±μ μμμ this
λ€μ λ©μλλ₯Ό μ μν λ μκΈ°λ λ¬Έμ λ₯Ό λ€μκ³Ό κ°μ μ½λλ‘ ν΄κ²°ν μ μλ€.
λͺ¨λ μΈμ€ν΄μ€λ area λ©μλλ₯Ό μμ νμ§ μμ§λ§ νλ‘ν νμ
κ°μ²΄μ area λ©μλλ₯Ό μ¬μ©ν μ μλ€.
// Circle μμ±μ
function Circle(center, radius) {
this.center = center;
this.radius = radius;
}
// Circle μμ±μμ prototype νλ‘νΌν°μ area λ©μλλ₯Ό μΆκ°
Circle.prototype.area = function () {
return Math.PI * this.radius * this.radius;
};
// Circle μμ±μλ‘ μΈμ€ν΄μ€ μμ±
var c1 = new Circle({ x: 0, y: 0 }, 2.0);
var c2 = new Circle({ x: 0, y: 1 }, 3.0);
var c3 = new Circle({ x: 1, y: 0 }, 1.0);