Javascript IIFE code sharing between projects - javascript

Looking for pure JavaScript answers please.
Using IIFE for a JavaScript game. Actually multiple games on multiple webpages. Suppose there is a common piece of code that needs to be used by all of these games. Say for example, a diceroller; 1d20, 3d6, etc.
What is the right way to do this? Should the IIFEs all be set to the global with unique names? I worry about setting to the global (perhaps I am too worried about that).
Does the diceroller need to be passed into the game IIFE? How to do this properly?

I think you want a Revealing Module Pattern, not an IIFE Pattern.
//Revealing Module Pattern (Public & Private) w Public Namespace 'game'
var game = (function() {
// object to expose as public properties and methods such as game.roll
var pub = {};
//game.roll
pub.roll = function () {
//do your thing
return randomIntFromInterval(1,6);
};
function randomIntFromInterval(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
//API
return pub;
}());

Related

Encapsulation in JavaScript with protoypes

Probably many of you tried to achieve encapsulation in JavaScript. The two methods known to me are:
a bit more common I guess:
var myClass(){
var prv //and all private stuff here
//and we don't use protoype, everything is created inside scope
return {publicFunc:sth};
}
and second one:
var myClass2(){
var prv={private stuff here}
Object.defineProperty(this,'prv',{value:prv})
return {publicFunc:this.someFunc.bind(this)};
}
myClass2.prototype={
get prv(){throw 'class must be created using new keyword'},
someFunc:function(){
console.log(this.prv);
}
}
Object.freeze(myClass)
Object.freeze(myClass.prototype)
So, as second option is WAY more convenient to me (specifically in my case as it visually separates construction from workflow) the question is - are there any serious disadvantages / leaks in this case? I know it allows external code to access arguments of someFunc by
myClass.protoype.someFunc.arguments
but only in case of sloppily executed callbacks (synchronously inside caller chain). Calling them with setTimeout(cb,0) breaks chain and disallows to get arguments as well as just returning value synchronously. At least as far as i know.
Did I miss anything? It's kind of important as code will be used by external, untrusted user provided code.
I like to wrap my prototypes in a module which returns the object, this way you can use the module's scope for any private variables, protecting consumers of your object from accidentally messing with your private properties.
var MyObject = (function (dependency) {
// private (static) variables
var priv1, priv2;
// constructor
var module = function () {
// ...
};
// public interfaces
module.prototype.publicInterface1 = function () {
};
module.prototype.publicInterface2 = function () {
};
// return the object definition
return module;
})(dependency);
Then in some other file you can use it like normal:
obj = new MyObject();
Any more 'protecting' of your object is a little overkill for JavaScript imo. If someone wants to extend your object then they probably know what they're doing and you should let them!
As redbmk points out if you need private instance variables you could use a map with some unique identifier of the object as the key.
So, as second option is WAY more convenient to me (specifically in my case as it visually separates construction from workflow) the question is - are there any serious disadvantages / leaks in this case?
Hm, it doesn't really use the prototype. There's no reason to "encapsulate" anything here, as the prototype methods will only be able to use public properties - just like your untrusted code can access them. A simple
function myClass2(){
var prv = // private stuff here
Object.defineProperty(this, 'prv', {value:prv})
// optionally bind the publicFunc if you need to
}
myClass2.prototype.publicFunc = function(){
console.log(this.prv);
};
should suffice. Or you use the factory pattern, without any prototypes:
function myClass2(){
var prv = // private stuff here
return {
prv: prv,
publicFunc: function(){
console.log(this.prv); // or even just `prv`?
}
};
}
I know it allows external code to access arguments of someFunc by
myClass.protoype.someFunc.arguments
Simply use strict mode, this "feature" is disallowed there.
It's kind of important as code will be used by external, untrusted user provided code.
They will always get your secrets if the code is running in the same environment. Always. You might want to try WebWorkers instead, but notice that they're still CORS-privileged.
To enforcing encapsulation in a language that doesn't properly support private, protected and public class members I say "Meh."
I like the cleanliness of the Foo.prototype = { ... }; syntax. Making methods public also allows you to unit test all the methods in your "class". On top of that, I just simply don't trust JavaScript from a security standpoint. Always have security measures on the server protecting your system.
Go for "ease of programming and testing" and "cleanliness of code." Make it easy to write and maintain, so whichever you feel is easier to write and maintain is the answer.

Javascript 'normal' objects vs module pattern

Currently I'm developing a large scale Javascript app(single page) and I've searched around the web to find some best practices. Most projects use the module pattern so the objects doesn't pollute the global namespace. At this moment I use normal objects:
function LoginModel(){
this.model = new MyModel();
this.getModel = function(){
return this.model;
};
}
This is readable and easy to maintain(my opinion). Is it better to use the module pattern just because of the namespacing or does it has other advantages I'm not aware of(counter memory leaks, ... )? Furthermore, I've already splitted up the files to have a nice MVC pattern and destroy every object when needed(counter memory leaks). So the main question is: do I need, in my case, to use the module pattern or not?
Module pattern:
var LoginModel = (function(){
var model = MyModel;
function getModel(){
return model;
};
return {
getModel: getModel
};
});
The module pattern is better for overall code organization. It lets you have data, logic and functions that are private to that scope.
In your second example getModel() is the only way to get the model from the outside. The variable declared int he module are hidden unless explicitly exposed. This can be a very handy thing.
And there's not really any drawback, other than being a little more complex. You just get more options for organization and encapsulation.
I'd use a plain object until my model gets complex enough to need more structure and some private scoping. And when you hit that point, it's trivial to redefine it as a revealing module without breaking any of the code that uses it.
If you're only going to be using one instance per page, I don't see the need to involve the new keyword. So personally I would create a revealing module like you did in your last example, and expose an object with the "public" properties.
Though I don't see your point with the getModel() function, since MyModel is obviously accessable outside of the scope.
I would have rewritten it slightly:
var LoginModel = (function(model, window, undefined){
function init(){ } // or whatever
function doSomethingWithModel(){
console.log(model);
}
return { init: init };
})(MyModel, window);
If you're uncertain of which modules that will get a model, you can use loose augumentation and change
})(MyModel, window);
to
})(MyModel || {}, window);
If you need several instances of a module, it would look something like this:
var LoginModel = (function(model, window, undefined){
function loginModel(name){ // constructor
this.name = name; // something instance specific
}
loginModel.prototype.getName = function(){
return this.name;
};
return loginModel;
})(MyModel, window);
var lm1 = new LoginModel('foo');
var lm2 = new LoginModel('bar');
console.log(lm1.getName(), lm2.getName()); // 'foo', 'bar'
There's several concepts conflated in your question
With what you call the "normal object", the function becomes a constructor function and requires the new keyword.
The second example uses the Revealing Module Pattern inside of an IIFE. This is the most popular variant of the Module Pattern, but unfortunately deeply flawed. For an explanation of the differences see my answer here, and for its flaws, see here.
Now, your question poses a false dichotomy -- normal objects or module pattern? You don't have to make a choice -- a normal object can use the module pattern simply by putting whatever it wants to keep private inside its closure scope. For example,
function LoginModel(){
var _notifyListeners = function(){
// Do your stuff here
};
this.model = new MyModel();
this.getModel = function(){
_notifyListeners();
return this.model;
};
}
This is an example of a "normal object" using the module pattern. What you have to avoid doing is what the Revealing Module Pattern does -- putting everything into closure scope. You should only put the things you want to keep private inside the closure scope.

jQuery namespace declaration and modular approach

I have confusion on how to proceed with my project.
I am developing an enterprise app in which lots of modules are to be written.
Most of module will be using lots of jQuery plugins to create complex grids, draw graphs for different purposes which means modules will be appending divs, tables etc a lot to DOM.
I want to preserver namespace since this will be large app.
For that I came across prototype method and self-executing anonymous function.
self-executing anonymous function seems to be recommended a lot.
My questions are
Are self executing functions reusable ?I mean these are immediately executed so lets say a module draws a complex grid for a given JSON file. So will I be able to use same self-executing anonymous function for 3 different JSON files just like a jQuery plugin ?
when there will be lots of modules written , they will all self execute on start-up. Will it effect Ram/Processor usage? Shouldn't it be way that modules should be called when needed ? what significance will self execution do ?
My Project Scope:
Kindly help me understand this self executing thing in my project scope, which is My project Holds a main namespace say "Myapp" and and its modules like Myapp.moduleA, Myapp.moduleB.MyApp will trigger its modules on click etc.
What is best way to go for me ?
Self-Executing Anonymous Func
(function( skillet, $, undefined ) {
//Private Property
var isHot = true;
//Public Property
skillet.somevar = "Bacon Strips";
//Public Method
skillet.draw = function() {
//Draw a grid
};
//Private Method
function _grid( ) {
//
}
}
}( window.skillet = window.skillet || {}, jQuery ));
You cannot reuse a self executing function, it just executes immediately and that's it.
If you need to execute it multiple times, you should just declare a function.
A possible approach is this:
var MYNAMESPACE.Object = (function(){
// private methods
var somemethod = function(){};
// public methods
return {
somepublicmethod: function(){}
};
})();
Now you can call it like this:
MYNAMESPACE.Object.somepublicmethod();
As for executing upon startup. Provided you only create methods and don't DO anything immediately inside your declaration, it won't affect performance too much unless you have a really big amount of modules. If that's the case, you should probably look into the asynchronous module loader pattern (AMD). RequireJS is a good example of that: http://requirejs.org
I wrote an article about JS namespaces which could be interesting for you:
http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/

Aliasing a function object in JavaScript

Disclaimer: I am using ExtJS 3, but I don't think it's very relevant to the question, outside of the common use of it's namespacing function.
I have a singleton that's declared in a really long namespace like this:
Ext.ns("REALLY.REALLY.LONG.NAMESPACE");
var Singleton = (function() {
var foo = {
bar: "baz"
};
var privateFunction = function(param){
// ...
return foo;
};
var single = Ext.extend(Object, {
constructor: function(config) {
Ext.apply(this, config);
},
otherFunction: privateFunction,
publicFunction: function (someObject){
// do stuff with someObject
}
});
return single;
})();
// Make it a singleton
REALLY.REALLY.LONG.NAMESPACE.Singleton = new Singleton();
I use it in other modules via calls like REALLY.REALLY.LONG.NAMESPACE.Singleton.otherFunction(); and REALLY.REALLY.LONG.NAMESPACE.Singleton.publicFunction(myObject); . I'm wondering if I can swap out those calls by setting up the client module with an alias to the singleton, i.e. var singleton = REALLY.REALLY.LONG.NAMESPACE.Singleton; , so that I can call singleton.otherFunction();. I'm wondering if this is an anti-pattern , or if there are any pitfalls (memory?) I might run into through this usage.
Thanks StackOverflow!
I'm wondering if I can swap out those calls by setting up the client module with an alias to the singleton
Yes, you can.
I'm wondering if this is an anti-pattern , or if there are any pitfalls (memory?) I might run into through this usage.
No, there aren't any that I can think of and it is faster than calling the fully-qualified version.
Local Alias Pattern
Example:
function somefunc(){
var singleton = REALLY.REALLY.LONG.NAMESPACE.Singleton;
singleton.publicFunction();
};
Or:
(function somfunc(singleton){
}(REALLY.REALLY.LONG.NAMESPACE.Singleton));
Test Results:
http://jsfiddle.net/jMg9A/
There is no issue with creating a reference to the original "object". In many cases we create a namespace to organize our code, but of course, this can lead to really long namespaces that we really don't wish to reference later, thus creating a local reference to that namespace is an excellent idea so that you can change it in one place instead of various places.
I don't really see an ant-pattern here, instead I see an opportunity to make it simpler for yourself and probably a little more manageable from a developer standpoint.

Howto move from object based language to server side Node.js Javascript for big projects?

I've decided to get used to using Javascript as my server sided (I'm using Node.js) language to setup a webserver, create server deamons and a lot more. This is a rather big project, which means that I have to get used to the language and get myself an optimal setup before actually starting to avoid overhead and unneeded hassle.
I have been looking for sources that'd explain the basics of functional programming in big projects. Unfortunately, most sources talk only about basic Javascript meant for simple tricks in a browser.
Two helpful links that explained how object creation works in Javascript were http://howtonode.org/object-graphs and http://howtonode.org/object-graphs-2.
In the end, it seems most wise to create an object like:
function MyObject(constructorMemberOne, constructorMemberTwo) {
this.constructorMemberOne = constructorMemberOne;
this.constructorMemberTwo = constructorMembertwo;
this.doSomething = function doSomething() {
//
}
}
Now, I'm looking for a complete Javascript language reference. So far, https://developer.mozilla.org/en/JavaScript/Reference seems to be most complete.
Q1: is this the recommended ECMAScript language reference? I'm asking mostly because it's sourced by a company that's mostly working in the browser industry, yet Javascript is not just there for browsers -- maybe there are sources that I'm unaware of.
Secondly, I'm used to creating a new file for every class I create where the file name represents the name of the class. Q2: Is this recommended practice in Javascript (V8, Node.js) too? How would one "import" this class?
This "importing" leads me to my confusingness about Node.js's "require". I know it's not the same. Require basically loads another file which then has it's own namespace, meaning that it's variables are out of the scope of the file that's requireing this file. For my classes however, I want to have methods that are available to the class that is "importing" (quotes as I am not sure whether this is even possible) this class. Eg.:
var utils = require("utils/MainUtils.js");
utils.doSomething();
As far as I know, this doSomething() method is only available if it was set like:
function MainUtils() {
exports.doSomething = function doSomething() {
//
}
}
Q3: Is that correct? Doesn't that seem quite abnormal?
Q4: Are there any other blogs or resources that are helpful in getting my setup working, like howtonode.org?
Finally, Q5: have there been any efforts into making all this inheritance, object creation, project structure, namespacing etc. easier for big projects? Any libraries or something for this purpose?
Hopefully my questions are clear. Any help is appreciated. Thanks.
is this the recommended ECMAScript language reference?
Well the official ECMAScript language reference is the ECMA-262 itself. But unfortunately this is completely unreadable even by the standards of standards documents.
ECMA do not produce any materials aimed at end-programmers and there's no one tutorial considered “best”. The MDC link looks decent, at least. (Most JavaScript tutorials are absolutely horrible and full of errors. Which is partly JavaScript's fault for having so many... quirky... features, but still.)
In the end, it seems most wise to create an object like:
There is unfortunately no widely-accepted-‘best’ way to implement a class/instance system in JavaScript. A lot of frameworks have their own systems, or you can brew your own. Your example code creates a new instance of each method for each object instance, which you might consider suboptimal compared to JS's native prototyping. (Normally this approach is used with a var that= this in the closure to avoid this-binding problems in callback code.) You would also need to exercise care in how you create subclasses and initialise them in the constructors.
See this question for a discussion on approaches to class/instance in JS.
I'm used to creating a new file for every class I create
Yeah, that's a Java wart you shouldn't bring to JS.
Keep your source files in manageable chunks of related classes and functions. Sometimes that will be one public class per file, more often it won't be.
How would one "import" this class?
JS itself has no native import functionality. In browsers you do it by inserting <script> tags or eval​ing code fetched by XMLHttpRequest, and have to take care of keeping variables in separate namespaces manually. In Node.js and other places where you're working with CommonJS, you use modules and require().
Is that correct?
Yes.
Doesn't that seem quite abnormal?
I don't think so. It's similar to other scripting languages, where it proves very useful. It's only really Java that forces you to wrap up a compilation unit into a single class.
I came up with the following after reading a book called Pro Javascript Design Patterns. However, I've been told that it's not good to think like this (private, public, static, etc.) in Javascript:
var SomeClass = (function() {
this.prototype.publicStaticMember = "this is a public static variable",
this.prototype.publicStaticMethod = function() {
return "this is a public method: cannot access private members/methods, but can access privileged and public members/methods";
}
var privateStaticMember = "this is a private static variable";
function privateStaticMethod() {
return "this is a private static method: can only access private members/methods";
}
//instance part
return function() {
this.publicInstanceMember = "this is a public instance variable";
var privateInstanceMember = "this is a private instance variable";
this.publicInstanceMethod = function() {
return "this is a privileged method: can access both public and private members/methods";
}
var privateInstanceMethod = function() {
return "this is a private method: can access both public and private members/methods but is private";
}
}
})();
It'd be instantiated like this:
var someInstance = new SomeClass().("param1", "param2");
Any comments? Should I read an other book?
If you haven't already, checkout the videos by Douglas Crockford. He has a bunch of videos that talk about the prototypal aspects of JavaScript.
Google for 'Douglas Crockford Java Programming Language Video'. Here is a link to the first part in the series: http://video.yahoo.com/watch/111593/1710507
The defineClass npm package provides simple yet powerful OOP for JavaScript with support for traits (mixins) and nested classes. Here is an example of usage:
var defineClass = require("defineClass").defineClass;
var Person = defineClass({
cash: 0,
constructor: function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
greet: function (name) {
console.log("Hello " + name + ". My name is " + this.firstName);
},
earn: function (amount) {
this.cash += amount;
}
});
var Developer = defineClass({
_super: Person,
// override a field default value
cash: 100,
// override the constructor
constructor: function (firstName, lastName, language) {
// you may have code before the base constructor call
// call the base constructor
this._super(firstName, lastName);
this.language = language;
}
// override a method
greet: function (name) {
console.log("Hey, " + name + ". I'm " + this.firstName)
},
// override a method and call its base method
earn: function (amount) {
return this._super(amount * 1.2);
}
});
Read more in the readme: https://github.com/nodirt/defineClass
Installation:
$ npm install defineClass

Categories

Resources