Questions about prototypes and inheritance processing on nodes.

Asked 2 years ago, Updated 2 years ago, 42 views

Questions about prototypes and inheritance processing on nodes.

I'm not good at handling prototypes yet. The source code below briefly blocked.

Please check why there is an error;;

;;;;

JavaScript Prototype and Inheritance Relationship

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

node.js javascript

2022-09-21 22:59

1 Answers

util.inherit links prototype inheritance.

SayHello1 is an instance property created within the constructor, so it is not accessible from the Child instance.

If you call Parent constructor as below inside Child constructor, sayHello1 will also be created in Child instance.

var Child = function(){
    Parent.call(this)
    this.sayHello3 = function(){
      console.log('3 :: Child Origin :: sayHello3()')
  }
}


2022-09-21 22:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.