0

So, as a work requirement our code cannot be larger than 80 columns and 250 rows. This means I have to go back and break up my code into smaller files and I am exploring a few options. First that came to mind was prototyping with JavaScript since I can't install RequireJS. Secondly, my application uses a closure. My question is this: can you prototype into a closure? Example below.

File #1

var app = (function () {
  var _userName = "Steve";
  function sayHello() {
    return "Hello " + _userName;
  }
  return {
    sayHello: sayHello
  }
})();

File #2

app.prototype.sayGoodbye = function() {
  return "Goodbye " + _userName;
};

Output

app.sayHello(); // should output "Hello Steve"
app.sayGoodbye(); // should output "Goodbye Steve"

However this does not seem to work, because the sayGoodbye() function is not included in the closure. But, if told the sayHello() function to use the sayGoodbye(), that also does not work. Any suggestions on how to construct a closure object across multiple files? Thanks!

xxSithRagexx
  • 193
  • 1
  • 1
  • 13
  • 1
    Your problem is that `var app;` is not returning an app object to do a prototype – Jorius Mar 23 '17 at 22:28
  • So, what if I did `(function app () { ... })();` then assign that to a variable, would that do the trick? – xxSithRagexx Mar 23 '17 at 22:29
  • wait for it, I'm writing an answer – Jorius Mar 23 '17 at 22:32
  • No, this has nothing to do with prototypes. Absolutely nothing. Forget them. – Bergi Mar 23 '17 at 23:16
  • Possible duplicate of [JavaScript - extract out function while keeping it private](http://stackoverflow.com/q/23364382/1048572) or [How do I give multiple JavaScript objects across multiple files access to same private variable?](http://stackoverflow.com/q/35529674/1048572) – Bergi Mar 23 '17 at 23:19

1 Answers1

1

You can change your closure function like this, this is a closure function that seems more like a class

var app = (function() {

  // This is your constructor
  function app() {
    this._userName = "Steve";
  }

  function hello() {
    return "Hello " + this._userName;
  }

  // This is made to do the above function hello() public
  app.prototype.sayHello = function() {
    return hello.call(this);
  }

  // Here we return the app object to be able to do a prototype
  return app;
})();

// Here we do our prototype
app.prototype.sayGoodbye = function() {
  return "Goodbye " + this._userName;
}

// Here we create an instance
var a = new app();

console.log(a.sayHello()); // should output "Hello Steve"
console.log(a.sayGoodbye()); // should output "Goodbye Steve"
Jorius
  • 204
  • 1
  • 3
  • 14