자바스크립트에서 상속은 프로토타입 객체의 속성을 후손 객체 마음대로 사용할 수 있다는 점을 사용해 상속을 구현한다.
function ClassA() {
this.a;
this.method1 = function () {
console.log('method1 is running');
}
}
let test1 = new ClassA();
test1.a = 'one';
function createObject(o) {
//빈생성자 함수 만듬
function F() {
};
//생성자 함수의 프로토타입객체를 매개변수로 넘어온 객체로 변경
F.prototype = o;
//생성자 함수를 실행해서 결과를 반환.
return new F();
}
// test2에 test1을 프로토 타입으로 가지고있는 객체 할당
let test2 = createObject(test1)
//test1에서 상속받은 속성 'a'를 대문자 'A'로 변경
test2.a = 'A';
//test2의 속성 d 추가
test2.b = 'two';
// test1에서 상속받은 method1을 변경
test2.method1 = function (){console.log('change method1')}
//콘솔로 확인
console.log(test2.a) //'A'
console.log(test2.b) // 'four/
test2.method1() // change method1
test1.method1() // method1 is running
'JavaScript' 카테고리의 다른 글
자바스크립트 ProtoType (0) | 2020.12.30 |
---|---|
자바스크립트의 객체2 (0) | 2020.12.30 |
자바스크립트의 객체1 (0) | 2020.12.30 |