mercredi 2 septembre 2015

Use the function inside another function as the constructor in javascript

I have the function structured this way because I need to inject it as a angularjs Factory. however, when I use it stand along to create a test for it, I encounter difficutly. I can NOT reference the ItemModel inside the ItemModelGenerator! I can not create an instance of it by using it as a constructor! I tried many many ways use keyword of new or invoke both, invoke either, pass arguments in bot or either, none of them works. I am confused...

Is this possible to somehow use this ItemModelGenerator as a constructor for another var? or, let say use the ItemModel inside it to generate, but in a condition that of course, the var has to be outside of ItemModelGenerator, because it is a factory.

I tried:

var Service = new ItemModelGenerator();
Service.ItemModel();

new ItemModelGenerator().ItemMode();

new ItemModelGenerator.ItemMode();

..etc

BTW, it does work as a angularjs factory injection, its tested.

Thanks

'use strict';
function ItemModelGenerator() {
  function ItemModel(inputItem) {
    var defaults = {
      id:'na',
      name:'na'
    };
    var location = inputItem ? inputItem : { defaults };
    this.id = location.id;
    this.name = location.itemName ? location.itemName : location.name;
    this.itemIsReal = this.isReal(this.id);
  }

  ItemModel.prototype.isReal = function(id) {
    return id !== false ? true : false;
  };

  return ItemModel;
}

Aucun commentaire:

Enregistrer un commentaire