Multiple Prototypes

0

I would like to know how to add a prototype to a function that is already instantiated in a prototype. Example below:

app.js

'use strict';

function NivFire(){
    this.db = "", this.admin = "", this.reference;
}

NivFire.prototype = {
    Fire : function(credential,url){},
    Ref : function(ref){ }
};

NivFire.prototype.Ref.prototype = {
    Set: (args) => {},
    Push: (args) => {}
};

module.exports = NivFire;

main.js

var NivFire = require("./app.js");
var nivfire = new NivFire();
nivfire.Fire( require('./nivellirfirebase.json'), "https://nivellir-97d87.firebaseio.com" );

nivfire.Ref("users").Set({
  name : "User1"
});

When this code is executed, it returns the TypeError: Can not read property 'Set' of undefined.

    
asked by anonymous 21.04.2018 / 21:55

1 answer

1

Use Object.defineProperty() to define a new property directly into an object, or modify an existing property in an object. To avoid repetitions of code and to facilitate maintenance, create a new module, here I give the file name as defineProperty.js

let config = {
  writable: false,
  enumerable: false,
  configurable: true
};

const definePropriedade = (obj, nome, valor) => {
  config.value = valor;
  Object.defineProperty(obj, nome, config);
}

module.exports = definePropriedade;

Then import into the file that will be used, in case app.js

let definePropriedade = require('./definePropriedade.js');

Now just call the method informing the prototype:

// Define a propriedade: "Fire"
definePropriedade(NivFire.prototype, 'Fire', (credential,url) => {
  console.log(credential, url);
});

When defining the property of a property, simply call the method back into itself and enter the value this as a prototype:

// Define a propriedade: "Ref"
definePropriedade(NivFire.prototype, 'Ref', (ref) => {
  console.log('Usando Ref: ${ref}');
  // Define a propriedade: "Set"
  definePropriedade(this, 'Set', (args) => {
    console.log('Usando Set: ${JSON.stringify(args)}');
  });
  // Define a propriedade: "Push"
  definePropriedade(this, 'Push', (args) => {
    console.log('Usando Push: ${JSON.stringify(args)}');
  });
  // Para que funcione "Ref('users').Set({ name : 'User1' })"
  // deve retornar o objeto
  return this;
});

See running at repl.it

Reference

25.04.2018 / 09:30