[Javascript] 상속

bunny.log·2022년 7월 24일

생성자 함수

var Human = function(type){
	this.type = type || 'human'; 
};

생성자 메서드(Static method)

Human.isHuman = function(human){
	retun Human instanceof Human;
}

인스턴스 메서드(prototype method)

Human.prptoype.breath = function(){
	alert('h-a-a-a-m');
};

ES6

class Human{
	constructor(type = 'human'){
    	this.type = type;
    }
    
    static isHuman(human){
    	retun Human instanceof Human;
    }
    
    breath(){
	    alert('h-a-a-a-m');
    }
}

기존 상속

var Nyh = function(type, firstName, lastName){
	Human.apply(this. arguments); // Human을 상속 받을때 
    this.firstName = firstName;
    this.lastName = laistName;
}

Nyh.prototype = Object.create(Human.protptype);
Nyh.prototype = constructor.Nyh; // 상속하는 부분
Nyh.prototype.sayName = function(){
	alert(this.firstName + '' + this.lastName);
};
var oldNyh = new Nyh('Human','bunny','nam');
Human.isHuman(oldNyh); //true

ES6 상속

class Nyh extends Human{
	constructor(type, firstName, lastName){
	    super(type);
        this.firstName = firstName;
    	this.lastName = laistName;
    }
    
    sayName(){
    	super.breath();
        alert(`${this.firstName} ${this.lastName}`);
    }
}
profile
더 많은 유익한 내용은 ->> https://github.com/nam-yeun-hwa

0개의 댓글