Search code examples
javascriptnode.jsprototypenode-modulesprototypal-inheritance

NodeJS calling prototype from another


I keep getting X is not a function when trying to use another method on the same object. Test code below:

OBJECT1 :

"use strict"

let Mod1OBJ = function () {}

Mod1OBJ.prototype.first = function first () {
  console.log('first')
}

exports.Mod1OBJ = new Mod1OBJ()

OBJECT2 :

"use strict"

const { Mod1OBJ } = require(`./mod1.js`)

let Mod2OBJ = function () {}

Mod2OBJ.prototype.second = function second () {
  Mod2OBJ.deferred()
  console.log('second')
}

Mod2OBJ.prototype.deferred = function deferred () {
  Mod1OBJ.first()
  console.log('deferred')
}

exports.Mod2OBJ = new Mod2OBJ()

Index.js:

"use strict"

const { Mod2OBJ } = require(`./lib/pack1/mod2.js`)
Mod2OBJ.deferred()
Mod2OBJ.second()

On execution:

first
deferred
/path to file/mod2.js:8
Mod2OBJ.deferred()
          ^
TypeError: Mod2OBJ.deferred is not a function

Clearly 'deferred' is a function on Mod2OBJ but not when called within another method on the same object.

I thought I understood how to use modules/require/prototyping but clearly, I don't - I'm pulling my hair out trying to work out what I'm doing wrong? Any help is greatly appreciated.


Solution

  • When you create an instance of an object all properties of prototype copy then after to that object. If you want to access before creating an instance of the object you can use prototype or this.

    Try this:

    Mod2OBJ.prototype.second = function second () {
      Mod2OBJ.prototype.deferred()
      console.log('second')
    }
    

    EDITED ======= Second way:

    Mod2OBJ.prototype.second = function second () {
      this.deferred()
      console.log('second')
    }