생성자 함수를 통한 상속

지환·2024년 6월 6일
0

자바스크립트

목록 보기
13/30

PersonPlus 보기

function Person(name,first,second){
    this.name = name;
    this.first = first;
    this.second = second;
}

Person.prototype.sum = function(){
    return this.first = this.second;
} // 모든 객체에서 공유하는 메소드를 만듦.


function PersonPlus(name,first,second,third){
    // this.name / this.first, second는 Person에서 사용하고 있어서 이 부분을 동일하게 사용하는게 아니라,
    // 다른 방법으로 사용하고 싶다면?
    Person(name,first,second); //Person 실행 >> 이렇게 하면 될까?

}

PersonPlus.prototype.avg = function(){
    return this.first + this.second + this.third / 3
}


var kim = new PersonPlus('kim',10,20,30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg());

이렇게 하면 안된다.

this에 집중해야됨.

Person.call이 하는 역할은 super(name,first,second); 이 부분을 의미한다.

class PersonPlus extends Person{
    constructor(name, first, second, third){
        super(name,first,second);
        this.third = third;
    }
    sum(){
        return super.sum() + this.third;
    }

    avg(){
        return (this.first + this.second + this.third) / 3
    }
}

2Step

function Person(name,first,second){
    this.name = name;
    this.first = first;
    this.second = second;
}

Person.prototype.sum = function(){
    return this.first = this.second;
} // 모든 객체에서 공유하는 메소드를 만듦.


function PersonPlus(name,first,second,third){
    // this.name / this.first, second는 Person에서 사용하고 있어서 이 부분을 동일하게 사용하는게 아니라,
    // 다른 방법으로 사용하고 싶다면?
    Person.call(this,name,first,second); //Person 실행 >> 이렇게 하면 될까?
    this.third = third;

}

PersonPlus.prototype.avg = function(){
    return this.first + this.second + this.third / 3
} // 지금 이렇게만 사용한다면 상속구조를 표현할 수 없음. 그렇게 되면 어떻게 해야될까?




var kim = new PersonPlus('kim',10,20,30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg());

PersonPlus 객체를 생성

kim.avg()를 실행하면?

sum이라는 메소드가 없어서 오류발생.

찾아서 수행할 수 있게 수정해줘야함.

PersonPlus.prototype.avg = function(){
    return this.first + this.second + this.third / 3
} // 지금 이렇게만 사용한다면 상속구조를 표현할 수 없음. 그렇게 되면 어떻게 해야될까?

이 부분을 수정해야함

PersonPlus.prototype.__proto__ = Person.prototype; // 여기를 수정해야함.

Object.create(Person.prototype); 
// 이렇게도 사용함.
// 이렇게 하면 새로운 객체가 생성됨.
// Person.__proto__로 하는 새로운 객체가 생성됨.


PersonPlus.prototype = Object.create(Person.prototype);


PersonPlus.prototype.avg = function(){
    return this.first + this.second + this.third / 3
} 


생성자 함수를 통한 상속 : constructor 속성은 무엇인가?

  • kim.constructor는 kim이라는 객체를 생성한 Person 생성자이다.
var d = new Date();
> undefined

Date.prototype.constructor === Date

> true

d.constructor

> Date(){[native code]} 

profile
아는만큼보인다.

0개의 댓글