Inheritance Patterns
9035 단어 JavaScriptJavaScript
Pseudoclassical
- 생성자(constructor) 함수를 선언 후 필요한 속성을 할당해준다.
var Mufasa = function() {
this.position = 'king';
this.name = 'father';
this.rakecolor = 'orange';
}
- prototype을 이용하여 필요한 메서드를 만들어준다.
Mufasa.prototype.hunt = function() {
return 'hyena';
}
- 자식 함수를 선언 후 call 또는 apply를 통해 부모 함수의 속성들을 호출해준다.
이때 속성의 값을 변경하고 싶을 경우 재할당해준다.
var Simba = function() {
Mufasa.call(this);
this.name = 'son';
this.friends = '';
}
- prototype을 이용하여 부모 객체와 자식 객체를 연결해준다.
Simba.prototype = Object.create(Mufasa.prototype);
- 아직 생성자는 부모 함수이기 때문에 자식 함수의 constructor를 자기 자신으로 재할당해준다.
Simba.prototype.constructor = Simba;
- 자식 함수에 메서드를 추가하고 싶을 경우 prototype을 이용하여 추가해준다.
Simba.prototype.play = function() {
this.friends = 'timon & pumbaa';
}
ES6 Class
- 부모 클래스 선언 후 생성자(constructor) 키워드를 사용하여 필요한 속성을 할당해준다.
- 필요한 메서드는 생성자 밖을 빠져나와 선언해준다.
class Mufasa {
constructor() {
this.position = 'king';
this.name = 'father';
this.rakecolor = 'orange';
}
hunt() {
return 'hyena';
}
}
- extends 키워드를 이용하여 자식 클래스 선언 후 부모 클래스의 생성자를 호출해준다.
- super 키워드를 사용하여 부모 클래스의 모든 속성들을 자동으로 상속시켜준다.
- 이때 속성값의 변경을 원할 경우 값을 재할당해준다.
class Simba extends Mufasa {
constructor() {
super();
this.name = 'son';
this.friends = '';
}
}
- 자식 클래스에 메서드를 추가하고 싶을 경우 constructor 밖을 빠져나와 선언해준다.
class Simba extends Mufasa {
constructor() {
super();
this.name = 'son';
this.friends = '';
}
play() {
this.friends = 'timon & pumbaa';
}
}
Author And Source
이 문제에 관하여(Inheritance Patterns), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@miraecod/Inheritance-Patterns저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)