Reputation: 300
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!
Upvotes: 0
Views: 84
Reputation: 204
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"
Upvotes: 1