velopert / learnjs

벨로퍼트와 함께하는 모던 자바스크립트
https://learnjs.vlpt.us/
85 stars 47 forks source link

10. 프로토타입과 클래스 · GitBook #8

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

10. 프로토타입과 클래스 · GitBook

undefined

https://learnjs.vlpt.us/basics/10-prototype-class.html

shoo7830 commented 5 years ago

class 마지막 예제에서 say() 관련 내용이 없어서 에러가 납니다.

kimuhjin commented 4 years ago

class Animal { constructor(type, name, sound) { this.type = type; this.name = name; this.sound = sound; }

say() { console.log(this.sound); // 이 함수 넣어줘야 합니다. } }

gangpyono commented 3 years ago

질문있습니다. 클래스를 사용하여 객체를 상속받을떄 상속받아 새로 생성하는 클래스의 constructor의 첫번쨰 파라미터는 왜 설정을 안해주는건가요?

KyungHwanLeeNexsol commented 3 years ago

질문있습니다. 클래스를 사용하여 객체를 상속받을떄 상속받아 새로 생성하는 클래스의 constructor의 첫번쨰 파라미터는 왜 설정을 안해주는건가요?

Animal 클래스를 상속받은 자식클래스 이름을 보면 Dog, Cat으로 설정했죠. 그럼 그 클래스를 사용하는 인스턴스의 type은 이미 개, 고양이로 하는것이라 그렇지 않을까요

minhos3389 commented 3 years ago

요새는 수정을 안해주시니 아쉽네요,,,

manbavaran commented 3 years ago

class Animal { constructor(type, name, sound) { this.type = type; this.name = name; this.sound = sound; } say() { console.log(this.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 cat = new Cat('야옹이', '야옹');

여기에서 왜 const dog나 cat에서 ('개', '멍멍이', '멍멍') 이런 식으로 안하고 super옆에 '개' 나 '고양이'를 쓰나요? super(type, name, sound) 이렇게 하면 에러가 나던데 왜 나는지 궁금해요.

wjdals108 commented 3 years ago

super 옆에 '개' 나 '고양이' 를 사용하는 이유는 아래의

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

와 같이 Dog 클래스와 Cat 클래스를 이용하여 객체를 생성할 때, dog 객체의 type 은 '개' 로, cat 객체의 type 은 '고양이' 로 따로 값을 넣어주지 않더라도 type 이 고정이 되어 있겠죠.

const dog2 = new Dog('멍멍이2', '멍멍멍'); const dog3 = new Dog('멍멍이3', '멍멍멍멍');

이런 식으로 하나의 Dog 클래스를 이용해서 여러개의 객체를 생성하더라도 type 은 '개' 로 고정을 시킬 수 있다는 장점? 이 있다고 생각하시면 이해가 되시지 않을까 싶네요. (Dog 클래스로 만든 여러개의 객체는 name 과 sound 는 다를 수 있지만 type 은 항상 개 이다)

super(type, name, sound) 이렇게 하면 에러가 나는 이유는

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

위의 코드에서 Dog 라는 클래스 아래의 constructor는 일종의 특별한 메서드라 생각하시면 됩니다. 이 메서드의 parameter 로 name, sound 가 있고, super 를 호출하는 상태인 것이죠. 그런데 이 메서드 안에서 type 을 사용하려고 하는데 이 type 은 class 내부, constructor의 parameter, 메서드의 내부 어디에도 선언되어 있는 부분이 없으니 type 이라는 것을 알 수가 없어서 에러가 터진다 이렇게 생각하시면 될 겁니다.

정확한 정보는 아닐 수 있으니, 참고만 하시길 바랍니다.

Jibros commented 2 years ago

22.03.22

zuzubibi commented 2 years ago

22.03.25

hdgpaul commented 9 months ago

231209

daeunkim99 commented 2 months ago

240621