Multiple Prototypes

Asked

Viewed 32 times

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: Cannot read Property 'Set' of Undefined.

1 answer

1


Use Object.defineProperty() to set a new property directly on an object, or modify an existing property on an object. To avoid code repetitions and facilitate maintenance, create a new module, here I give the file name as definePropritaty.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 in 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 again within 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;
});

Behold running on repl.it

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.