Coding Style in node.js - javascript

Style 1: Objects with constructor/prototype
function DB(url) {
this.url = url;
}
DB.prototype.info = function (callback) {
http.get(this.url + '/info', callback);
};
Style 2: Closures
function DB(url) {
return { info: async.apply(http.get, url + '/info') };
}
This is just an example and assume that there are more prototype methods and private methods involved.
I have read in posts One and Two that closure style is much more preferred in nodejs over the other. Please help me clarify why using this.something syntax is bad in nodejs.
You can give your opinion about which is better, but I mostly need to know about what are the advantages and disadvantages of each style when used in nodejs.

It's not about a style. These two functions do two completely different things.
Closure provides an access to local variables. This way you can create private variables that aren't accessible from the outside (like url in your example). But it has a performance impact since closure is created each time your object is created.
Prototype function is faster, but it is created before object, and don't know anything about an object itself.
Sometimes it even makes sense to use both of them at the same time. :)
PS: coding style is described here: https://npmjs.org/doc/coding-style.html . It doesn't explain your particular question, but I feel I have to balance those two links in previous answer with something more sensible. :)

Closures, when done correctly, allow you to encapsulate data through the use of the scope chain that cannot be modified by any other caller.
The prototype chain does not provide any protection in that same sense. The main drawback to the use of Objects in the fashion you describe, especially in a server or library scenario, is that the "this" keyword can be modified by the caller. You have no control over that and your code will break in wildly unpredictable ways if it occurs.
var mongo = new DB('localhost');
mongo.info.call(this); // broken
Now it may not happen as explicitly as that but if you are passing around objects or object properties as event handlers, callbacks, etc into other functions, you have no way of knowing - or protecting against - that type of usage. So the bottom line is that the 'this' keyword is not something you can bank on. While you can completely control your immediate scope with the use of closures.
In a similar vein, you also have no guarantee that your object's prototype chain has not been altered. Unless, of course, you are creating a closure over the object and returning a wrapper.
Lastly, the closure structure more closely follows the Law of Demeter since your object would, theoretically, be "reaching through" via the prototype chain. Using a closure to encapsulate other calls allows you to expose a single method which can result in calls to another service methods. This provides greater maintainability and flexibility since you now control the methods you expose directly without relying on the prototype chain. Of course, the LoD is just one way of doing things so that may or may not be important to you.

Node follow javascript standards. So any javascript coding style is a proper coding style for node.js. But the following links may give you the abbreviation of node.js coding style.
http://nodeguide.com/style.html
http://innofied.com/javascript-coding-standards-follow/

I use sjsClass: https://www.npmjs.org/package/sjsclass
Code example:
Class.extend('DB', {
'protected url': null,
__constructor: function (url) {
this.url = url;
},
info: function (callback) {
http.get(this.url + '/info', callback);
}
});

There are benefits to both styles and i think it depends on what your module/file is trying to expose. I heavily use closure style for most modules i use in my code. (like db abstraction, cache abstraction, mail etc..) and i use constructors/prototype for objects i create a lot of (like a node in a doubly-linked-list)
=== objects with attributes defined inside a closure
if you create an object (lets call it self),
inside its scope add a bunch of methods that access and attach to that object (self.x)
and at the end export self, everything has access only to what you added to self and cannot access the local variables inside the function where you created self
=== constructors and prototype
on the other hand if you create constructors and add methods/fields to them trough prototype every function that attaches itself to your instance has access to its internal variables and state.
==
there are some things that work easier with prototypes like EventEmitter
and Streams but it not very hard to attach them to objects also.
Javascript is both an object oriented language and functional language, and missing the heavy lifting tools on both sides
like proper inheritance ever seen this.super().super().someMethod() ?? I havn't
(you need it if both superclasses have the same method name)
or nomads or simple generators at the side of functional programming.
so for me it makes sense to use both, and pick the one that's most suited to your problem.
EDIT
There is one big benefit for objects which i totally forgot about.
In your second example you use a flow control library (async in this case but any defered library will do), it makes your code so much cleaner, however
for your example to work the get method of http.get has to be bound to http, which in many cases it is not. so then your code will look like http.get.bind(http)
if http were an object and get was defined in its scope it would always work and allows you to pass it around to other code. (like async)

IMHO this is discussion is larger than node ... it's about javascript language.
So I suggest read this:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
and google a lil about javascript design patterns!

constructor can be use like that
var db = new DB();
...
if(db instanceof DB){
...
}
Closures can make private variables like
function DB(url) {
var urlParam = '&a=b';
return {
info: async.apply(http.get, url + '/info' + urlParam)
};
}
urlParam is a private variables cannot be get or set
if you only want a static class or simple class, use Closures.

Related

what does function () {} mean when assigned to a variable

I know that functions are objects in javascript, and that functions can be assigned to variables. I am also aware of this question: How does the (function() {})() construct work and why do people use it?.
But I would like to know precisely what does it mean in this context:
https://github.com/zsolt/retwis-nodejs/blob/master/domain.js#L43
User = function(){}
This line is followed by the declaration of some member functions (methods?) of the "supposed" User object.
It seems there is no other explanation answer here in SO.
It means User is a function that takes no inputs, has no side effects and returns nothing.
Most likely it is a class constructor and methods will be added to it later. User.foo = function() { /* ... */} would imply a static method, so this is more like a utilities class if you're used to thinking in Java architecture.
You should look up pseudo-classical inheritance in Javascript. Analogizing to Java, the code would be adding static methods to the User class, not object.
I'm still pretty convinced the code is following Java class patterns because the writer would prefer User to be a constructor that can be instantiated, has static methods, and has no instance methods (that I saw), over an object with properties that are functions. You are right that this is circuitous, but it's what the writer would do if they are a Java developer. It does have the advantage that instance methods may be added to User later with little client-code impact but I see no evidence this will happen to User (I didn't look long).
By the way, I deduced this because CapitalizedNames for functions implies it should be called with new in Javascript engineering in general, which implies it's a class. Figuring out why a class might be preferable just has to do with Java experience.
The canonical way to create an object in Javascript is:
function user(config) {
this.config = config;
...
}
User = new user(config);
It uses this context (and concept). This format is used if you want to create named properties and/or methods.
If you don't need to create this context you may use just following:
User = function(){}
Here the constructor function is anonymous and doesn't create any context. For the same reason the new keyword is not needed.

Javascript: Function that returns an object containing other functions? What is this called?

I am somewhat new to Javascript (been using it for a few months), but overall I would probably consider myself a borderline novice/intermediate programmer. I am now working on a fairly large project in Javascript, containing many different functions, and I am trying to figure out some "best practices" for organizing my code.
I have seen a few examples of an approach that seems potentially very helpful. For example, see this Stackoverflow answer, or this page on best practices (do a Ctrl+F for return{). Essentially, you define a function in a variable, and that function simply returns other functions/variables:
var functionContainer = function() {
return {
function1 : function () {
// Do something
},
function2 : function () {
// Do something else
}
};
}();
This seems helpful in cases where I have multiple functions that do similar things; I can put them all into a "container" of sorts, and then call them with functionContainer.function1();.
Essentially, my question is: Is there a name for this technique? Can you recommend any sources for further reading? A lot of sources that I've seen don't go into great depth about what exactly is going on when you do this, and I want to be sure that I fully understand what I'm doing before I start shuffling around a bunch of my code.
I may post some separate follow-up questions later, depending on the responses I get here. If so, I will post links to them here, for anyone else who's curious.
Revealing Module Pattern
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
Addy Osmani's Analysis copied from link above:
Advantages
This pattern allows the syntax of our scripts to be more consistent.
It also makes it more clear at the end of the module which of our
functions and variables may be accessed publicly which eases
readability.
Disadvantages
A disadvantage of this pattern is that if a private function refers to
a public function, that public function can't be overridden if a patch
is necessary. This is because the private function will continue to
refer to the private implementation and the pattern doesn't apply to
public members, only to functions.
Public object members which refer to private variables are also
subject to the no-patch rule notes above.
As a result of this, modules created with the Revealing Module pattern
may be more fragile than those created with the original Module
pattern, so care should be taken during usage.
That is just assignment and learning about how in javascript functions are first class types. You also have an object literal as well in there being returned with some functions defined as members. It's kind of like a revealing module pattern though for a proper approach I recommend the following reading:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
This is a just a simple object literal. Contrary to some of the other answers, it is not the revealing module pattern. In the revealing module pattern, your functions would be defined in the closure, not in the returned object literal.
However, I think your code is in error. I think you meant to write
var functionContainer = (function() {
return {
function1 : function () {
// Do something
},
function2 : function () {
// Do something else
}
};
})();
With this code, you can call functionContainer.function1();. (removed: You could not do that with your original code.) If this pattern is what you meant, then it is an IIFE returning an object literal.

Using Function.prototype.bind or saved reference

This is subjective (opinion based) - but only to a degree, don't rush voting to close. Causing some arguments at work as everyone has a different opinion and people are trying to enforce a single way of doing it.
Simple context: when you have the option to save a reference in your closure to the instance or to use a polyfilled Function.prototype.bind, what possible disadvantages do you see to either approach?
To illustrate possible usecases, I just made up some class methods.
Pattern one, saved ref:
obj.prototype.addEvents = function(){
var self = this;
// reference can be local also - for unbinding.
this.onElementClick = function(){
self.emit('clicked');
self.element.off('click', self.onElementClick);
};
this.element.on('click', this.onElementClick);
};
Pattern two, a simple fn.bind:
obj.prototype.addEvents = function(){
// saved reference needs to be bound to this to be unbound
// once again, this can be a local var also.
this.onElementClick = function(){
this.emit('clicked');
this.element.off('click', this.onElementClick);
}.bind(this);
this.element.on('click', this.onElementClick);
};
Pattern two and a half, proto method to event:
obj.prototype.addEvents = function(){
// delegate event to a class method elsewhere
this.element.on('click', this.onElementClick.bind(this));
};
obj.prototype.onElementClick = function(){
this.emit('clicked');
this.element.off('click', this.onElementClick); // not matching due to memoized bound
};
Personally, I am of the opinion that there isn't a single correct way of doing this and should judge on a per-case basis. I quite like the saved reference pattern where possible. I am being told off.
Question recap:
Are there any GC issues to be considered / be mindful of?
Are there any other obvious downsides or pitfalls you can think of on either method?
Polyfill performance or event native .bind vs a saved ref?
My personal preference is to use the saved reference method. Reasoning about the value of this can be very hard sometimes because of how JavaScript treats this.
The bind is nice but if you miss the .bind(this) it looks like a bug.
The latter exposes too much; every time you need a callback you'd need to expose another helper in your API.
There are many ways to use prototyping. I think the most important thing is to pick one and stick to it.
Are there any GC issues to be considered / be mindful of?
Older engines don't infer what variables are still used from the closure and do persist the whole scope. Using bind does make it easy because the context is explicitly passed and the un-collected scope does not contain additional variables.
However, this doesn't make a difference if you're using a function expression anyway (as in patterns #1 and #2).
Are there any other obvious downsides or pitfalls you can think of on either method?
Saving reference:
needs an additional line for declaring the variable, sometimes even a whole new scope (IEFE)
Code can't be easily moved because you need to rename your variable
Using bind:
Easily overlooked on the end of a function expression (just like the invocation of an IEFE), it's not clear what this refers to when reading from top to bottom
Easily forgotten
I personally tend to use bind because of its conciseness, but only with functions (methods) declared elsewhere.
Polyfill performance or event native .bind vs a saved ref?
You don't care.
In your example, you actually don't need that reference to the bound function and the off method. jQuery can take care of that itself, you can use the one method for binding fire-once listeners. Then your code can be shortened to
obj.prototype.addEvents = function(){
this.element.one('click', this.emit.bind(this, 'clicked'));
};

Example of situation that needs declaring a method inside the constructor function instead of declaring it as a prototype method

I understand that prototype method is shared by all instances of an object in JavaScript.
I can't think of a practical example when you will need the other situation—declaring the method inside the constructor function and thus making every instance of the object having it's own instance of the method. Can you provide a case for this?
The primary use is emulating private fields. See my answer here for an example:
Declaring javascript object method in constructor function vs. in prototype
I agree with #Raynos to an extent - it does feel like an unnecessary and futile practice to implement private state at the cost of efficiency.
In general it’s necessary to create functions when any sort of state-binding is required. So it could be of practical value when you need to pass functions around that refer explicitly to the object state. If you’re going to incur the penalty each time you create a state-bound function then you are at a plus if you bind it just once in the constructor and reference that single bound function rather than creating it multiple times.
State binding is sometimes necessary by design choices out of your own hands. It would make sense for example to create state-bound event handlers for an object on initialisation.
but I can't think of a practical example when you will need the other situation
That's because there is no practical example.
Declaring functions inside the constructor is a known bad practice due to incurring unnecessary performance penalties.
It should also be noted that prototypes are awesome because they encourage extensibility, flexibility and monkey patching. Meaning that you can fix someone else's objects because everything can be intercepted and manipulated.
Closures are like frozen objects, they remove flexibility from you and are a nightmare to manipulate, wrap or alter.
It should be noted you don't need to use prototypes and can use functions instead if that pleases you
function cake(fruits, chocolate, size) {
return {
slice: function () {
return cakeSliceList(this)
},
toString: function () {
return "A lovely cake containing " + fruits.toString()
+ ", " + chocolate.toString()
},
weight: function () {
return size * CAKE_SIZE + fruits.weight() + chocolate.weight()
}
}
}
A functional style is valid, combining the functional style together with prototypes get's rather silly, rather quickly.
If you are using closures anywhere in your object, and need to reference them inside your function. Or, alternatively, if you specifically want to make your function "private".
Of course, this begs the question of under what circumstances you want to use closured variables. The 'private' argument may popup here again. Additionally, here is a discussion as to some common uses of closures.

How to Implement Closures Using SpiderMonkey API?

I've been working with the SpiderMonkey C API and would like to implement a closure in C using their API. The one I would like to implement is fairly complex, but I can't even figure out how to do a simple one such as:
function x() {
var i = 0;
return function() { i++; print(i); };
}
var y = x();
y(); //1
y(); //2
y(); //3
I was wondering if anyone knows how I might do this. I found the JS_NewFunction method, but I don't actually know if that is a step in the right direction. Any help will be appreciated, thanks!
I don't know if there's a pure C way of doing closures or not. I would reccomend though, if you can, to just implement the functionality you need in javascript, and simply evaluate the javascript text in JSAPI. From there, use JSAPI to grab whatever handles/variables you need to implement your host functionality. It's really onerous to do javascripty things using JSAPI, avoid it if you can.
Narrated as if you're probably still interested, a year later.
Knitting my brows furiously at the documentation for JS_GetParent, I see
For some functions, it is used to implement lexical scoping (but this is an implementation detail).
and then, along with a list of API functions that create functions,
Some of these functions allow the application to specify a parent object. If the JSAPI function creating the object has a parent parameter, and the application passes a non-null value to it, then that object becomes the new object's parent. Otherwise, if the context is running any scripts or functions, a default parent object is selected based on those.
I might experiment with this later, but it seems that you might be able to do this either by (merely) creating the function in the API during the execution of the function that you want it to have the scope of.
Otherwise, you might be able to set the lexical scope of a function to some object manually using JS_SetParent, but the documentation keeps ominously calling that use of parents 'internal'.
</necro>

Categories

Resources