노드에서 프로토타입과 상속처리에 대한 질문입니다.

조회수 2898회

노드에서 프로토타입과 상속처리에 대한 질문입니다.

아직 프로토타입을 잘 다루지 못하는지라.. 아래 소스코드에서 잠깐 막혔습니다.

왜 오류가 발생하는지 확인좀 부탁드립니다;;

발생하는 문제 및 실행환경

자바스크립트의 프로토타입과 상속관계

에러메시지

TypeError: obj3.sayHello1 is not a function
    at Object.<anonymous> (C:\Users\DEV05\Desktop\nodejs\workspace\hello_basic\h
ello_inherit.js:50:6)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:134:18)
    at node.js:962:3

소스코드

var util = require('util');

//define Parent Class
var Parent = function(){
  this.sayHello1 = function(){
      console.log('1 :: Parent Origin :: sayHello1()');
  };
};
Parent.prototype.sayHello2 = function(){
    console.log('2 :: Parent Prototype :: sayHello2()');
}

//define Child Class
var Child = function(){
    this.sayHello3 = function(){
      console.log('3 :: Child Origin :: sayHello3()');
  };
};
Child.prototype.sayHello4 = function(){
    console.log('4 :: Child Prototype :: sayHello4()');
}

//use Parent's Function by Parent
var obj1 = new Parent();
console.log('============================================');
console.log('[log] obj1 :: ', obj1);
obj1.sayHello1();
obj1.sayHello2();

//use Parent's Function by Child
var obj2 = new Child();
console.log('============================================');
console.log('[log] obj2 :: ', obj2);
obj2.sayHello3();
obj2.sayHello4();

//apply inherits
util.inherits(Child, Parent);
console.log('============================================');
console.log('[log] Parent :: ', Parent);
console.log('[log] Child :: ', Child);
console.log('[log] Parent.prototype :: ', Parent.prototype);
console.log('[log] Child.prototype :: ', Child.prototype);


//show inherited Child
var obj3 = new Child();
console.log('============================================');
console.log('[log] apply inherits Parent() to Child() ');
obj3.sayHello1();  //error
obj3.sayHello2();  //error

1 답변

  • util.inherits 는 prototype 상속을 연결해줍니다.

    sayHello1는 constructor 안에서 생성되는 instance property이기 때문에 Child instance에서 접근이 안되죠.

    Child constructor 내부에서 Parent constructor를 아래처럼 불러주시면 Child instance에도 sayHello1이 생성됩니다.

    var Child = function(){
        Parent.call(this)
        this.sayHello3 = function(){
          console.log('3 :: Child Origin :: sayHello3()')
      }
    }
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)