๐ Prototype ์ ๋ฆฌ
https://manon-kim.tistory.com/129
ES5 - Object.create( )
Object.create()
: ES5 ๋ ๋์จ ์์์ด์ฉํ์ฌ ์ฝ๊ฒ object ๋ง๋๋ ๋ฐฉ๋ฒ
Object.create(๋ถ๋ชจobject) : ์๊ดํธ์์ ์ ์ ๋ถ๋ชจ object๊ฐ prototype์ด ๋๋ค.
let ๋ถ๋ชจ = { name : 'Kim', age : 50 };
let ์์ = Object.create(๋ถ๋ชจ);
console.log(์์.age);
//์ถ๋ ฅ : 50
์์์ด ์์ฑ์ ๋ฐ๊พธ๊ณ ์ถ์ผ๋ฉด ๊ฐ์ ์๋ก ๋ถ์ฌํด์ฃผ๋ฉด ๋๋ค.
let ๋ถ๋ชจ = { name : 'Kim', age : 50 };
let ์์ = Object.create(๋ถ๋ชจ);
์์.age = 20;
console.log(์์.age);
//์ถ๋ ฅ : 20
? ์ ๋ถ๋ชจ์ ์์๊ฐ์ด ์ถ๋ ฅ๋์ง์์ ?
: javascript object ์๋ฃํ์์ ํน์ ์๋ฃ๋ฅผ ๊บผ๋ผ ๋ ๋ฌป๋ ์์๊ฐ
1. ํด๋น object๊ฐ ์ง์ ๊ทธ ๊ฐ์ ๊ฐ์ง๊ณ ์์ผ๋ฉด ๊ทธ๊ฑฐ ์ถ๋ ฅ
2. ์์ผ๋ฉด ๋ถ๋ชจ์ prototype ์์ ์ฐพ์์ ์ถ๋ ฅ
3. ๋ ์์ผ๋ฉด ๋ถ๋ชจ์ ๋ถ๋ชจ (...๋ฐ๋ณต...) ํด์ ์ถ๋ ฅํ๋ค.
์ด๋ฐ์์ผ๋ก ์์์ ์์ฃผ๊น์ง ๊ฐ๋ฅ~
let ๋ถ๋ชจ = { name : 'Kim', age : 50 };
let ์์ = Object.create(๋ถ๋ชจ);
์์.age = 20;
let ์์ = Object.create(์์);
console.log(์์.age);
// ์ถ๋ ฅ : 20
ES6 - Class / construtor
class / construtor
: ES6 class ์ ๋ฌธ๋ฒ์ผ๋ก constructor ์์ฑ
์ด๋ ๊ฒ class๋ก๋ถํฐ ์๋ก ์์ฑ๋ object๋ฅผ instance๋ผ๊ณ ํ๋ค.
class ๋ถ๋ชจ {
constructor(){
this.name = 'Kim'
}
}
let ์์ = new ๋ถ๋ชจ();
์์๊ฐ๋ฅํ ํจ์ ์ถ๊ฐ ๋ฐฉ๋ฒ 2๊ฐ์ง
1. constructor ์์ ์ถ๊ฐ
class ๋ถ๋ชจ {
constructor(){
this.name = 'Kim';
this.sayHi = function(){ console.log('hello') }
}
}
let ์์ = new ๋ถ๋ชจ();
2. prototype์ ์ถ๊ฐ
: object์ ํจ์ ์ถ๊ฐ ํ๋ฏ์ด ํ๊ฑฐ๋
class ๋ถ๋ชจ {
constructor(์ด๋ฆ, ๋์ด){
this.name = ์ด๋ฆ;
this.age = ๋์ด;
}
sayHi(){
console.log('Hi');
}
sayHello(){
console.log('Hello');
}
}
let ์์ = new ๋ถ๋ชจ('Park', 28);
๋ถ๋ชจ.prototype.sayHi = function ( ) { } ๋ก ํด๋๋๋ค.
Class - extends / super
๐ป ๋ค๋ฅธ class๋ฅผ ์์ํด์ ์๋ก์ด class๋ฅผ ๋ง๋ค ๋ extends๋ฅผ ์ด๋ค.
extendsํ class์์๋ super( )๋ฅผ ์ถ๊ฐํ๋ค.
super๋ 'extends๋ก ์์์ค์ธ ๋ถ๋ชจ class์ constructor()'์ ์๋ฏธํ๋ค.
super์๋ ์์๋ฐ์ class์ ํ๋ผ๋ฏธํฐ๋ฅผ ๊ทธ๋๋ก ์ถ๊ฐํด์ค์ผํ๋ค. (ํ๋ผ๋ฏธํฐ ์๋ช ์ ์์ ๋กญ๊ฒ ๊ฐ๋ฅ)
// ๊ธฐ์กด class
class dog {
constructor(a, b) {
this.type = a;
this.color = b;
}
}
// ๊ธฐ์กด dog class๋ฅผ ๊ฐ์ ธ์์ ์๋ก์ด class ์์ฑ
class cat extends dog {
constructor(c) {
super();
this.age = c;
}
}
class๊ฐ์ ํจ์ ์์๋ฐ๊ธฐ
: ๋๊ฐ์ด super๋ก ๊ฐ์ ธ์จ๋ค.
class dog {
constructor(a, b) {
this.type = a;
this.color = b;
}
sayHello() {
console.log("์๋
๋๋ ๊ฐ");
}
}
class cat extends dog {
constructor(a, b, c) {
super(a, b);
this.age = c;
}
sayHello2() {
console.log("์๋
๋๋ ๊ณ ์์ด");
super.sayHello();
}
}
let cat1 = new cat("์ฝ์", "whtie", 5);
console.log(cat1.sayHello2());
//์ถ๋ ฅ : ์๋
๋๋ ๊ณ ์์ด, ์๋
๋๋ ๊ฐ
'ARCHIVE > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] ๋น๋๊ธฐ / Promise / async.await (0) | 2022.01.06 |
---|---|
[JS] getter,setter / import,export (0) | 2022.01.05 |
[JS] ๊ฐ์ฒด์งํฅ (Constructor, Prototype) (0) | 2021.12.28 |
[JS] this (0) | 2021.11.13 |
[JS] Error (Try catch & throw) (0) | 2021.09.22 |