[js] 프로토타입/클래스

young0_0·2022년 11월 15일
0

js

목록 보기
5/10

생성자 함수 (constructor)

함수를 통해 새로운 객체를 만들고 그 안에 넣고 싶은 값, 함수들을 구현 할수 있게 해준다.

  • 객체 생성자 함수는 대문자 로 한다.
  • 새로운 객체를 만들때는 new 키워드를 앞에 붙인다.
  • this 는 생성자 함수자신을 가르키며 this 에 저장된 것들은 new 를 통해 객체를 만들 때 그 객체에 적용된다.
function Animal(type,name,sound){
	this.type = type;
 	this.name = name;
  	this.sound = sound;
  	this.say = function(){
    	console.log(this.sound)
    }
}

const dog =  new Animal('개','초코','왈왈')
const cat = new Animal('고양이','존떡','야옹')

dog.say() // 왈왈
cat.say() // 야옹

프로토타입(prototype = 원형(원래의모습))

  • 모든 객체가 공유하고 있어서 한번 만들어진다.
  • this.say 보다 Animal.prototype.say 이 더 효율적이다.(this에 넣은 것은 객체 하나를 만들 때마다 메소드도 하나씩 만들어 지기 때문에 메모리 낭비가 발생한다.)
function Animal(type,name,sound){
	this.type = type;
 	this.name = name;
  	this.sound = sound;
}

Animal.prototype.say = function (){
	console.log(this.sound)
}

const dog =  new Animal('개','초코','왈왈')
const cat = new Animal('고양이','존떡','야옹')

dog.say() // 왈왈
cat.say() // 야옹

상속

  • 부모 생성자의 기능을 물려받는 동시에 새로운 기능을 추가 할수 있는것
function Animal(type,name,sound){
	this.type = type;
 	this.name = name;
  	this.sound = sound;
}

Animal.prototype.say = function (){
	console.log(this.sound)
}

function Dog(name, sound){
	Animal.call(this,'개',name,sound)
}
Dog.prototype = Animal.prototype;

function cat(name, sound){
	Animal.call(this,'고양이',name,sound)
}
cat.prototype = Animal.prototype;


const dog =  new Dog('초코','왈왈')
const cat = new Cat('존떡','야옹')

dog.say() // 왈왈
cat.say() // 야옹

클래스(Class)

  • 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의 하는 틀
  • 상속 할 때는 extends
  • super()함수가 상속 받은 클래스의 생성자를 가르킨다.
class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
}

class Dog extends Animal {
  constructor(name, sound) {
    super('개', name, sound);
  }
}

class Cat extends Animal {
  constructor(name, sound) {
    super('고양이', name, sound);
  }
}

const dog = new Dog('멍멍이', '멍멍');
const dog2 = new Dog('왈왈이', '왈왈');
const cat = new Cat('야옹이', '야옹');
const cat2 = new Cat('냐옹이', '냐옹');

dog.say();
dog2.say();
cat.say();
cat2.say();

출처:https://learnjs.vlpt.us/

profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

0개의 댓글