[02/23]

송승찬·2020년 2월 25일
0

CodeSquad_TIL

목록 보기
3/14

Prototype

class Animal {
constructor (name,age) {
this.name=name;
this.age =age;
}
run() {
console.log(${this.name}이 열심히 달리네)
}
setName (name) {
this.name = name;
return this;
}
info () {
console.log(name is ${this.name},age is ${this.age})
}
}

const animal=new Animal('호랑이',29).setName('Seoul').run()

const animal1 = new Animal('Moon',30);
animal1.protoype.seoul = ()=>{
this.name = 'HI'
}
const animal2=new Animal()
animal2.prototype.lite =()=>{

}
//overriding
animal1.prototype = {
constructor : animal1,
info () {

},
eat () {

}
}
console.log(animal1,animal2)

animal1.info === animal2.info//(메모리상에서 같은 곳(주소)를 가리키고 있기에)

//method추가
Animal.prototype.seoul =() => {

}
//proto === prototype
// constructor에 있는 것만 객체를 찍을 때 나오고, 그 외의 프로퍼티나 메서드는
// instance.proto에 존재(인스턴스들이 이 녀석들을 같이 공유하기 위해서)
// proto는 인스턴스에 뭔가 추가할 때 사용, 클래스에 추가할 때는 안먹힘
// prototype은 클래스에 뭔가 추가할 때 사용, 인스턴스에 추가할때는 instance.prototype이 undefined라 안 먹힘

a.proto.constructor

//proto는 내가 만든 객체에(인스턴스) 접근할 때, prototype은 클래스 자체에 접근할 때

//클래스안에서 정의한 constructor와 proto에 있는 constructor는 다른애들
// proto의 constructor는 클래스 전체를 가리킨다
class Animal {
constructor (name,age) {
this.name=name;
this.age =age;
}
run() {
console.log(${this.name}이 열심히 달리네)
}
setName (name) {
this.name = name;
return this;
}
}
// a.proto.proto.constructor
// ƒ Object() { [native code] }
// a.constructor
class Animal {
constructor (name,age) {
this.name=name;
this.age =age;
}
run() {
console.log(${this.name}이 열심히 달리네)
}
setName (name) {
this.name = name;
return this;
}

profile
superfly

0개의 댓글