728x90
๊ฐ์ฒด ์์ฑ ๋ฐฉ์
1 ) ๊ฐ์ฒด ๋ฆฌํฐ๋ด, 2)์์ฑ์ ํจ์, 3) Object.create()
๊ฐ์ฒด ๋ฆฌํฐ๋ด ๊ฐ์ฒด ์์ฑ์, ์ปจํ ์ธ ๋ฅผ ๊ทธ๋๋ก ๋์ ์ฐ์๋ ๊ตฌ์กฐ์ฒด, ์ฐ๊ด๋ ๋ฐ์ดํฐ๋ฅผ ์ผ์ ํ ๋ฐฉ๋ฒ์ผ๋ก ๋ณํํ๊ณ ์ ํ ๋ ๋ง์ด์ ex) ์๋ฒ์๊ฒ ์ฃผ์๋ฅผ DB์ ๋ฃ์ด๋ฌ๋ผ๊ณ ์์ฒญํ ๋, ํ๋์ ๊ฐ์ฒด๋ก ์ ์กํ๋ค. (๊ฐ ์์ดํ ๋ค์ ํ๋ํ๋ ๊ฐ๋ณ ์ ์กํ์ง ์์) |
ํด๋์ค new ์ฐ์ฐ์๋ก ๊ฐ์ฒด ์ธ์คํด์ค ์์ฑ extends ํค์๋๋ก ์์ ํน์ ๊ตฌ์กฐ์ ๊ฐ์ฒด๋ฅผ ์ฌ๋ฌ๊ณณ์์ ์ฌ์ฉํด์ผ ํ๋ ๊ฒฝ์ฐ ํด๋์ค๋ก ํ์ํ ๋๋ง๋ค ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ฉด ์ฌ์ฌ์ฉ์ฑ, ์ ์ง๋ณด์ ํธ๋ฆฌํจ ๋ฑ ์ฅ์ ์ด ์์ต๋๋ค. |
1) ๊ฐ์ฒด ๋ฆฌํฐ๋ด const person = {
name: "๊ธธ๋",
age:21,
printName(){
console.log(`${this.name}`)
}
}
1. key ๊ฐ์ด ์ซ์๋ก ์์ํ๊ฑฐ๋, ๊ณต๋ฐฑ, ํน์๋ฌธ์๋ฅผ ํฌํจํ ๊ฒฝ์ฐ ''๋ฅผ ๋ถ์ฌ์ ์ฌ์ฉ var emoticon= {'^^': 'smile'};
var id = { '0A': 10};
์ด ๊ฒฝ์ฐ, ๋๊ดํธ [ ] ๋ฅผ ์ด์ฉํด์๋ง ํธ์ถ์ด ๊ฐ๋ฅํ๋ค. console.log(emoticon['^^']) // smile
2. key๊ฐ์ ๋ณ์๋ก ํธ์ถ ๊ฐ๋ฅ ์ด ๊ฒฝ์ฐ์๋, ๋๊ดํธ [ ] ๋ฅผ ํตํด ์ ๊ทผ var profile = {
age : 10,
name : '์ฒ ์'
}
var key = 'name';
console.log(profile.key);
console.log(profile[key]); // '์ฒ ์'
3. ํ๋กํผํฐ ์ถ์ฝ var name = 'bar';
// ์ถ์ฝ
var foo = {
name
};
console.log(foo.name) // 'bar' 4. key์ ๊ณ์ฐ์ ์ฌ์ฉ var num1 = 1;
var num2 = 2;
var strHello = 'hello';
var newObj = {
[1 + 1]: 'first',
[num1 + num2]: 'second',
[strHello + num1]: num2,
[`${strHello} - ${num1 + num2}`]: 'fourth'
};
console.log(newObj);
//{ '2': 'first', '3': 'second', hello1: 2, 'hello - 3': 'fourth' }
|
2) ์์ฑ์ ๋ฐฉ์ 2-1 . new Object() : new ์ฐ์ฐ์๋ฅผ ํตํด Object ๊ฐ์ฒด์ ์์ฑ์ ํจ์๋ฅผ ํธ์ถ var myObj = new Object();
myObj.name = '์นด๋ ์ ';
myObj['age'] = 20;
myObj.hello = function(){
return `์ด๋ฆ์ ${this.name}์ด๊ณ , ๋์ด๋ ${this.age}์
๋๋ค.`;
};
2-2. new ์ฌ์ฉ์ ์ ์ ์์ฑ์ : ์ง์ ์์ฑ์ ํจ์๋ฅผ ๋ง๋ค์ด ๊ฐ์ฒด๋ฅผ ์์ฑ class Person { constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first}`);
}
}
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting();
|
3) Object.create() : ํ๋กํ ํ์ ์์์ ํตํด ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๋ฐฉ์ var parent = {a:10, b:20};
var child = Object.create(parent);
console.log(child.a); // 10
|
this / ์ง์ ๊ฐ์ฒด ์ฐ๊ธฐ
this.name(o) / person.name(x)
๋ง์ฝ ๋ ๊ฐ์ ๋ค๋ฅธ person ๊ฐ์ฒด๊ฐ, ๊ฐ๊ฐ ๋ค๋ฅธ ์ด๋ฆ์ผ๋ก ์ธ์คํด์ค๊ฐ ์์ฑ๋ ์ํ์์ ์ด๋ฆ ์ถ๋ ฅ์ ์ํด name์ ์ฐธ์กฐํ ๋,
-> ๋ฉค๋ฒ ์ปจํ์คํธ๊ฐ ๋ฐ๋๋ ๊ฒฝ์ฐ์๋ ์ ํํ ๊ฐ์ ์ฌ์ฉํ๊ฒ ํด์ค๋ค. this๋ ์คํ์ค์ธ ์ฝ๋๊ฐ ์ํด์๋ ๊ฐ์ฒด๋ฅผ ์๋ฏธํ๊ธฐ ๋๋ฌธ
์ฐธ๊ณ ํ ๋ธ๋ก๊ทธ๊ธ
[JS] ์๋ฐ์คํฌ๋ฆฝํธ: ES6 ๊ฐ์ฒด ๋ฆฌํฐ๋ด ๊ธฐ๋ฅ 3๊ฐ์ง
728x90
'javascript > ES6' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ES6 javascript : ๋น๋๊ธฐ ์ฒ๋ฆฌ(callback, Promise, Generator) (0) | 2022.01.27 |
---|---|
ES6 javascript : setTimeout vs setInterval - ํธ์ถ ์ค์ผ์ค๋ง ํจ์ (0) | 2022.01.26 |
ES6 javascript ๊ฐ์ฒด : ์ ๋๋ ์ดํฐ(Generator), ๋น๋๊ธฐ (0) | 2022.01.24 |
ES6 javascript ๊ฐ์ฒด : ํ๋กํ ํ์ (prototype), __proto__ (0) | 2022.01.19 |
ES6 javascript : Symbol(์ฌ๋ณผ) (0) | 2022.01.18 |