๊ฐ์ฒด๋ฅผ ์์ฑํ๋ 3๊ฐ์ง ๋ฐฉ๋ฒ ์ค ํ๋๋ฅผ ์ดํด๋ณด์ ์๋์ ์ฝ๋๋ฅผ ์ด์ฉํ์ฌ person1, person2, person3๋ฅผ ๋ ๋ง๋ค ์ ์๋ค. ๊ทธ๋ฌ๋ ์ฌ๊ธฐ์ name , age๋ ๋ค๋ฅผ ์ ์์ผ๋ sayHello ๋ฉ์๋๋ฅผ ๋ชจ๋ ๊ฐ์ ์ญํ ์ ์ํํ๋ค.
๊ทธ๋ฌ๋ฏ๋ก ์ด ๋ฉ์๋๋ฅผ ํ๋๋ง ์ ์ธํ๊ณ ๋ชจ๋ ๊ณต์ ํ๋ฉด ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ ์ฝํ ์ ์์ ๊ฒ์ด๋ค ์ด๋ sayHello๋ฉ์๋๋ฅผ prototype์ผ๋ก ์ง์ ํ๋ ๊ฒ์ด๋ค.
function Person(name,age){
this.name=name;
this.age = age;
this.sayHello = function(){
console.log(` Hello ${this.name}`);
}
};
var person1= new Person('Jane',30)
var person2= new Person('Tom',30)
var person3= new Person('John',30)
console.log(person1)
console.log(person2)
console.log(person3)
Person.prototype.sayHello = function(){
console.log(` Hello ${this.name}`);
}
ํน๋ณํ ํ ๋นํ์ง ์๋๋ผ๊ณ ๋ชจ๋ ํจ์๋ ๊ธฐ๋ณธ์ ์ผ๋ก โprototypeโ ํ๋กํผํฐ๋ฅผ ๊ฐ๋๋ฐ ๋ํดํธ ํ๋กํผํฐ prototype์ constructor ํ๋กํผํฐ ํ๋๋ง ์๋ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ฉฐ constructor ํ๋กํผํฐ๋ ํจ์์์ ์ ๊ฐ๋ฆฌํจ๋ค. ๊ทธ๋ฌ๋๊น constuctor ํ๋กํผํฐ๋ ์๋ฐ์คํฌ๋ฆฝํธ ์์ง์ด ํ๋กํ ํ์ ์์ฑํ ๋ ์๋ฌต์ ์ผ๋ก ์ถ๊ฐํ ํ๋กํผํฐ์ด๋ค
const Person =(function (){
function Person(name){
this.name = name;
}
**Person.prototype.sayHello = function(){
console.log(`Hi, My name is ${this.name}`)
}**
return Person;
}());
const me = new Person('Lee');
>Person.prototype
// {sayHello: ฦ, constructor: ฦ}
>Person.constructor === Person // false
>me.constructor === Person // ture
>me.constructor === Object // false
const Person =(function (){
function Person(name){
this.name = name;
}
**Person.prototype ={
sayHello(){
console.log(`Hi, My name is ${this.name}`)
}**
}
return Person;
}());
const me = new Person('Lee');
>Person.prototype // {sayHello: ฦ}
>Person.constructor === Person // false
**>me.constructor === Person // false
>me.constructor === Object // true**
์์ ์ฝ๋๋ ๋ํดํธ prototype๋ฅผ ๋ฎ์ด์จ์ constructor๊ฐ ์์ด์ง๊ฒ์ด๋ค. ๊ทธ๋์ ์๋์ฒ๋ผ ์ฝ๋๋ฅผ ๋ฐ๊พธ๋ฉด
Person.prototype ={
constructor : Person,
sayHello(){
console.log(`Hi, My name is ${this.name}`)
}
}
**>me.constructor === Person // ture
>me.constructor === Object // fasle๊ฐ ๋์จ๋ค**
class Car{
constructor(color){
this.color= color;
this.wheels =4;
}
drive(){
console.log('DRIVE')
}
stop(){
console.log('STOP')
}
}
class Bmw extends Car{
constructor(color){
// super(color); ๋ถ๋ชจ๊ฐ์ฒด์ ํ์๋๋ก
this.navi = 1; // ์๋ฌ
}
park(){
console.log('PARK')
}
stop(){
super.stop();
console.log('stop...')
}
}
const x5 = new Bmw('red')
class์์ constructor ์์ฑํ ๋ ๋จผ์ ๋น ๊ฐ์ฒด { }๋ฅผ ๋ง๋ค๊ณ this ๋ก ์ด ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋๋ค. ๊ทธ๋ฐ๋ฐ extends ๋ฅผ ์ฌ์ฉํ ๊ฐ์ฒด๋ ์ด๊ณผ์ ์ ๊ฑด๋๋ฐ๊ธฐ ๋๋ฌธ์ ๋ฐ๋์ super()๋ฅผ ์ฌ์ฉํ์ฌ constructor๋ฅผ ์คํํด์ผ ํ๋ค.
๋ง์ฝ ์์ ๊ฐ์ฒด์ contructor๊ฐ ์๋ค๋ฉด ์๋ฌต์ ์ผ๋ก ๋ถ๋ชจ์ contructor๋ฅผ ์คํํ๋ค
class Bmw extends Car{
constructor(...args){
super(...args);
}
function Shape(){
}
Shape.prototype.duplicate = function(){
console.log('duplicate')
}
function Circle(radius){
this.radius = radius;
}
// ๋์ค์ ์ฌ๊ธฐ์ ์ถ๊ฐ
Circle.prototype.draw = function(){
console.log('draw')
}
const s = new Shape()
const c = new Circle(1)