const person = {
name: ["Bob", "Smith"],
age: 32,
bio: function () {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf: function () {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
person.name;
person.name[0];
person.age;
person.bio();
// "Bob Smith is 32 years old."
person.introduceSelf();
// "Hi! I'm Bob."
// Same thing
const person = {
name: ["Bob", "Smith"],
age: 32,
bio() {
console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
},
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
The value of an object member can be pretty much anything β in our person object we've got a number, an array, and two functions.
The first two items are data items, and are referred to as the object'sΒ properties. The last two items are functions that allow the object to do something with that data, and are referred to as the object'sΒ methods.
An object like this is referred to as anΒ π₯object literalΒ β we've literally written out the object contents as we've come to create it. This is different compared to objects instantiated from classes, which we'll look at later on.
JavaScriptλ νλ‘ν νμ κΈ°λ° μΈμ΄μ λλ€. μ΄λ JavaScriptμμ κ°μ²΄ μ§ν₯ νλ‘κ·Έλλ°μ΄ νλ‘ν νμ μ κΈ°λ°μΌλ‘ νλ€λ κ²μ μλ―Έν©λλ€. λ€λ₯Έ μΈμ΄λ€μ΄ ν΄λμ€(class)λ₯Ό μ¬μ©νμ¬ κ°μ²΄λ₯Ό μμ±νλ λ°λ©΄, JavaScriptλ νλ‘ν νμ μ μ¬μ©ν©λλ€
κ°λ¨ν μ€λͺ νλ©΄, JavaScriptμμλ λͺ¨λ κ°μ²΄κ° λ€λ₯Έ κ°μ²΄λ‘λΆν° μμλλ€λ κ°λ μ΄ μ€μν©λλ€. μ΄λ μμμ κΈ°λ°μ΄ λλ κ²μ΄ νλ‘ν νμ μ λλ€.
κ°μ²΄λ νλ‘ν νμ κ°μ²΄λ₯Ό κ°μ§κ³ μκ³ , μ΄λ₯Ό ν΅ν΄ λ€λ₯Έ κ°μ²΄λ‘λΆν° μμ±κ³Ό λ©μλλ₯Ό μμλ°μ΅λλ€. κ°μ²΄λ₯Ό μμ±ν λ, ν΄λΉ κ°μ²΄μ νλ‘ν νμ μ μ§μ νκ±°λ κΈ°μ‘΄ κ°μ²΄λ₯Ό μμ νμ¬ μλ‘μ΄ κ°μ²΄λ₯Ό λ§λ€ μ μμ΅λλ€.
// νλ‘ν νμ
κ°μ²΄ μμ±
var animal = {
eat: function () {
console.log("λ¨Ήλ€");
},
};
// μλ‘μ΄ κ°μ²΄ μμ± λ° νλ‘ν νμ
μ§μ
var dog = Object.create(animal);
dog.bark = function () {
console.log("μ§λ€");
};
dog.eat(); // "λ¨Ήλ€"
dog.bark(); // "μ§λ€"
μ΄ μμ μμ dog
κ°μ²΄λ animal
κ°μ²΄λ₯Ό νλ‘ν νμ
μΌλ‘ κ°μ§κ³ μμ΅λλ€. λ°λΌμ **dog
**λ eat
λ©μλλ₯Ό μμλ°μ μ¬μ©ν μ μμ΅λλ€.
μ΄λ¬ν νλ‘ν νμ κΈ°λ°μ μ κ·Ό λ°©μμ JavaScriptλ₯Ό μ μ°νκ² λ§λ€μ΄μ£Όλ©°, ν΄λμ€ κΈ°λ° μΈμ΄μλ λ€λ₯Έ κ°λ μ κ°μ§κ³ μμ΅λλ€. ES6λΆν°λ ν΄λμ€(class) λ¬Έλ²μ΄ μΆκ°λμμ§λ§ μ¬μ ν νλ‘ν νμ λ ν¨κ» μ¬μ©ν μ μμ΅λλ€.
μΌλ°μ μΈ λ°©μμΌλ‘λ μμ±μ μμ±μμμ, λ©μλλ νλ‘ν νμ μμ μ μν©λλ€. μμ±μμλ μμ±μ λν μ μλ§ μμΌλ©° λ©μλλ λ³λμ λΈλμΌλ‘ ꡬλΆν μ μμΌλ μ½λλ₯Ό μ½κΈ°κ° ν¨μ¬ μ¬μμ§λλ€.
// μμ±μμμ μμ± μ μ
function Test(a, b, c, d) {
// μμ± μ μ
}
// 첫 λ©μλ μ μ
Test.prototype.x = function() { ... };
// λλ²μ§Έ λ©μλ μ μ
Test.prototype.y = function() { ... };
// κ·Έ μΈ.