Emanegux
Emanegux

Reputation: 1120

How to create a function that allows its functions to use its other function's functions

I am familiar with structuring a class and instantiating it into an object in Javascript like the following:

var app = (function(){

  function Entity(){
    this.property = "string";
  }
  Entity.prototype.changeProperty = function(param){
    this.property = param;
  }

  var object = new Entity();
  object.changeProperty("number");
  console.log(object);

})();

The console log appears as follows:

enter image description here .

But I'm have trouble utilizing modular usability of functions in JS. The following is my attempt to grant one function's namespace to another:

var appEx = (function(){

  var Model = function(){
    function Entity(){
      this.property = "word";
    } 
    Entity.prototype.changeProperty = function(param){
      this.property = param;
    } 
  };

  var Router = (function(Model){
    var object = new Entity();
    object.changeProperty("number");
    console.log(object)
  })(Model);

})();

But this results in my class being unrecognized. What is the most simple way of doing this?

Upvotes: 3

Views: 170

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11340

You need to expose the object somehow:

var appEx = (function(){

  var Model = function(){
    function Entity(){
      this.property = "word";
    } 
    Entity.prototype.changeProperty = function(param){
      this.property = param;
    }
    return Entity;
  }();

  var router = (function(Model){
    var object = new Model();
    object.changeProperty("number");
    console.log(object)
  })(Model);

})();

Basically, return Entity from Model's iffy and call its object from within router.

Upvotes: 1

Related Questions