728x90
반응형
728x90
반응형

상속(Inheritance)

객체지향에서 중요한 개념입니다. 객체라는 것은 하나의 컨테이너이고 객체는 변수, 메소드로 모아져있습니다. 객체의 특성을 물려받아 새로운 객체를 만들수 있습니다. 새로운 객체는 부모 객체와 동일한 기능을 가질 수 있습니다. 부모의 기능을 그대로 사용하거나 추가할 수 있습니다. 이것이 바로 상속의 기본적인 동작 방식입니다. 이를 통해 로직을 재활용 할 수 있습니다.

부모의 재산을 자식이 상속받듯이 오리지널 객체의 기능을 동일하게 받을 수 있습니다.

function Person(name){

    this.name = name;

    this.introduce = function(){

        return 'My name is '+this.name;

    }  

}

var p1 = new Person('egoing');

document.write(p1.introduce()+"<br />"); // My name is egoing

 

function Person(name){ //생성자를 만들어서

    this.name = name;

}

Person.prototype.name=null; //객체의 prototype이라는 프로퍼티가 있는데 .name시 이름을 준다.

Person.prototype.introduce = function(){

    return 'My name is '+this.name;

}

var p1 = new Person('egoing');

document.write(p1.introduce()+"<br />");

자바스크립트의 상속 구현에 대해 알아보겠습니다.

function Person(name){

    this.name = name;

}

Person.prototype.name=null;

Person.prototype.introduce = function(){

    return 'My name is '+this.name;

}

 

function Programmer(name){

    this.name = name;

}

Programmer.prototype = new Person(); //상속받음

 

var p1 = new Programmer('egoing'); //Programmer생성자 호출

document.write(p1.introduce()+"<br />");

 

객체가 기능을 물려받았으니 새로운 기능을 추가하는 방법에 대해 알아보겠습니다.

Programmer.prototype.coding = function(){

    return "hello world";

}

document.write(p1.coding()+"<br />"); // hello world가 출력

 

function Designer(name){

    this.name = name;

}

Designer prototype = new Person();

Designer.prototype.design = function(){

    return "beautiful!";

}

var p2 = new Designer('leezche');

document.write(p1.introduce()+"<br />");

document.write(p1.design()+"<br />"); //beautiful!을 출력

 

prototype 원형(원래 형태)

객체지향 언어와 자바스크립트를 구분하는 개념

생성자는 기본적으로 함수입니다. 함수를 호출할 때 new로 인해 단순한 함수가 아닌 생성자로 변합니다. 새로운 객체를 만들어 리턴합니다. 어떤 객체를 만들 때 객체가 가져야 하는 메소드, 데이터가 주어지길 바라기 때문에 생성자를 사용합니다.

function Ultra(){}

Ultra.prototype.ultraProp = true;

 

function Super(){}

Super.prototype = new Ultra();

 

function Sub(){}

Sub.prototype = new Super();

Sub.prototype.ultraProp = 2;

var o = new Sub();

console.log(o.ultraProp); //true를 출력

sub객체는 ultraProp을 갖고 있지 않습니다. Sub의 부모인 super, super의 부모인 Ultra가 갖고 있습니다.

생성자는 기본적으로 함수입니다. 함수를 호출할 때 new를 붙이면 단순한 함수가 아닌 생성자 함수가 됩니다. 새로운 객체를 만들어 리턴합니다. o라는 변수는 sub()라는 생성자 함수에 의해 만들어진 객체입니다. 빈 객체를 만드는 것이 생성자라면 의미가 없습니다. 어떠한 객체를 만들 때 객체가 갖고 있어야하는 메소드, property값을 가져야합니다.

var o = new Sub();

//o.ultraProp = 1;

console.log(o.ultraProp); //2를 출력

1. 객체 o에서 ultraProp를 찾습니다..

2. 없다면 Sub.prototype.ultraProp를 찾습니다.

3. 없다면 Super.prototype.ultraProp를 찾습니다.

4. 없다면 Ultra.prototype.ultraProp를 찾습니다.

이는 객체와 객체를 연결하는 체인의 역할을 하는 것입니다. 이러한 관계를 prototype chain이라고 합니다.


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

+ Recent posts