Javascript Module Design - javascript

I was wondering if someone could explain the difference between these two JavaScript modules. I have been trying to learn how to design javascript modules by reading some underscore.js and jQuery source code, amongst others and have noticed these two patterns.
Example 1
(function() {
var _this = this;
_this.VERSION = '0.1';
}).call(this);
Example 2
(function(_this) {
_this.VERSION = '0.1';
}(this));

call(obj[, arg[, arg[, arg[, ...]]]]) runs function in obj context, function () {}(obj) will run function in current context passing obj in arguments. In this particular example there is no difference - both examples will do same thing. For some people it is just cleaner to run anonymous function with call or apply instead of just () and I think here it is the case.
In second example line with var _this = _this; is useless, _this is already defined within scope and that line is redefining already existing variable with same value (so its even incorrect).

Example 1 explicitly sets the value of the this variable within the function.
In Example 2 the function does not care about the value of this. It rather expects an argument that it can work with. You also could say that it does not rely on the value of this. An advantage of this pattern is that by the name of the parameter it can be made clear what you want (window, myObjectContext ...).
In your specific case it does not make a difference. But if the function contained code that made actual use of this, e.g. this.myObject = {}, it could make a difference, because this could have a different value in each case. But to be true, someone using the second pattern would never reference this within the function.

Related

Differences Between Named and Unnamed Anonymous Javascript Functions

Normally, in Javascript, when I want to pass an anonymous/inline function as an argument to another function, I do one of the following.
someFunctionCall(function() {
//...
});
someFunctionCall( () => {
//...
});
However, I've recently inherited a codebase that uses named function as inline arguments, like this
someFunctionCall(function foo() {
//...
});
I've never seen this syntax before. The function still seems to be anonymous -- there's no foo function defined in either the calling or called scope. Is this just a matter of style, or can using a named function (foo above) as an anonymous function change the behavior or state of that program?
This is specifically for a NodeJS (not a browser based program) program, and I'm specifically interested in behavior specific to using functions as parameters. That said information from behavior across platforms and runtimes is welcome.
There are at least three advantages of using named function expressions instead of anonymous function expressions.
Makes debugging easier as the function name shows up in call hierarchy.
The function name is accessible in the inner scope of the function, so it can be used for recursion
The function name itself acts like a self documentation of what the function is doing instead of reading the code.
Using those "named anonymous functions" won't change the behavior but will show the function name in stack traces which is very useful. Also the function gets callable within itself that way.
I'll give an example
Case 1:
var obj = {count: 0, counter: ()=> {this.count+=1;}}
If you do console.log(obj.count) you'll get 0
Case 2:
var obj = {count: 0, counter (){this.count+=1;}}
In 2nd case if you do console.log(obj.count) value will be one.
Hope you understood by now. Lamda expressions cannot access values with reference of this object. It can only access variables with global reference.
In case 1 if you want to make it work with lamba you have to use obj.count+=1 with name has reference.
And rest of the JavaScript function implementation remains same there is not much difference.

In JavaScript, what is the purpose of self-calling `call`?

I'm maintaining a javascript library whose original author is not longer working at the company.
I've found the following pattern repeated across the library:
var events = {}; // defined globally
// many lines below within a function:
if(!events.hasOwnProperty.call(events, eventKey)) return;
Does the use of call in that way offer any technical advantage over just doing:
if (!events.hasOwnProperty(eventKey)) return;
I feel like the former is less intuitive than the latter, and the latter is more expressive assuming the output is identical
Both are the same! There is no diffrerence. Any Object {} has the method hasOwnProperty() (Object.prototype.hasOwnProperty), what is a function (or function object) and any function (-object) has a method call() (Function.prototype.call) mdn-docs
And the first argument of Function.prototype.call() is the »this context/object«, or context/sidecar/this/that/etc…
So, in your case: events.hasOwnProperty.call(events, …) is just the very same as events.hasOwnProperty(…), since in the first case events will be this, because it was used as first argument to call(). In the latter case, events will also be this, since JS will always set the context/this automatically on each objects' method, if you do obj.method().
Or in code:
var
A = { log: console.log(this) },
B = {};
A.log() // A
A.log.call(A) // A
A.log.call(B) // B

jQuery on change refer to this.value and this

Let's say I have a bit of code like this that runs on change of a select:
$('select[name="nights"]').on('change', function() {
console.log(this.value);
});
Is there any way I can have a reference to my global this object(if it's called that) without using something like:
var self = this;
Using something like a bind destroys the reference to the jQuery select element:
$('select[name="nights"]').on('change', function() {
console.log(this.value);
});
I wan't to be more concise and understanding of scope though so I prefer binding rather than saving reference to this. If I look at code standards from airbnb for example they rather not use self = this reference as well.
https://github.com/airbnb/javascript#naming--self-this
I am wondering how they get around this like stuff though where you both need a local scope reference to this and a this reference to your global object.
Am I simply forced to still make a reference or is there any way around this? I might simply be overthinking and nitpicking here but I am hoping for an elegant solution, else I might as well stick with saving references in the first place.
I'm not sure weather I understand your question.
With #bind (ES5 way)
$('select[name="nights"]').on('change', function(){
console.log(this.value);
}.bind(this));
From https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
ES6 way
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Lexical this
Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.
An arrow function does not create its own this context; rather, it captures the this value of the enclosing context, so the following code works as expected.(I didn't copy the code)
so, you can to it with arrow function
$('select[name="nights"]').on('change', () => {
console.log(this.value);
});
NOTICE:
In your case i think you want to access the value of the select element, if so you
can use :
$(this).val();
instead of
this.value;
If you want to access the global this value, which is Window in the browser platform, you have two options:
Option 1:
If you want the ES5 way you can use an IIFE function, for example :
var that = (function(){return this;}());
option 2:
If you want the ES6 way, which is better with less code to write, for example:
const that = (()=>this)(); // .... (*)
Where (*) is the equivalent of the previous ES5 code.

What's the advantage of using `var self = this` in knockout.js view models [duplicate]

This question already has answers here:
var self = this?
(8 answers)
Closed 9 years ago.
I see in almost all examples of a knockout.js viewmodels the line var self = this and then all local variables are references as self.variableName. What is the advantage of this over using this.variableName?
Normally the main reason for using this approach is to make the current this available to subfunctions or closures. For example:
var myObject = {
param: 123,
method: function(){
alert( this.param );
},
method2: function(){
setTimeout(function(){
alert( this.param );
},100);
}
}
In the above calling myObject.method will give you the correct alert of 123. However calling myObject.method2 will give you undefined. This is because this inside the anonymous function used with setTimeout does not refer to myObject, depending on the JavaScript interpreter it will point to different things. However, if you have:
method2: function(){
var self = this;
setTimeout(function(){
alert( self.param );
},100);
}
This works because the current state of this — at the right point — is captured, and will always reference myObject for every function scope that it is available to.
The problem is not limited to the use of setTimeout. At any point where you have anonymous functions, subfunctions or closures this trick will come in handy. Sometimes people use self, or that or something a bit more descriptive depending on what the current reference represents.
rather than storing as a variable
There is an alternative to using self or any other variable to "remember" the state of this at any particular point, and that is to "bind" your anonymous or sub functions with a particular context. Many modern interpreters now support the Function.prototype.bind method, which can be used thusly:
var method = function(){
console.log(this);
};
var methodWithWindow = method.bind(window);
var methodWithDocument = method.bind(document);
var methodWithObject = method.bind({random:"object"});
Calling each of the bound methods in turn would give you the following console output:
Window
Document
Object {random:"object"}
If you wish to support older browsers you can use a polyfill, or if you prefer a much simpler implementation, one that doesn't worry about binding arguments as well. The basics of what the bind code does is the following:
!Function.prototype.bind && (Function.prototype.bind = function(context){
var method = this;
return function(){
method.apply(context, arguments);
}
})
So, how would the initial example look using bind?
method2: function(){
setTimeout((function(){
console.log(this); // `this` will be the same as the `this` passed to bind.
}).bind(this),100);
}
As you can see above, once bound, the returned function (closure) retains that specified context; so it can be passed around where ever you want and still keep a this reference to the object you want. This is useful in the method2 example because we bundle the method up with our current context and pass it to setTimeout which will execute the bound method later (long after we have exited the current block execution).
The same does occur for when using self or any other variable. The variable would be captured within the function's scope chain, and would still be there for access when the function is eventually called again. The benefit of using bind however is that you can override the context easily if you so wish, you would have to code your own specific methods to do so to override a self variable.
WARNING: It is worth noting here that when you bind a function, a new function is returned. This can cause confusing situations if you mix bound functions with event listeners and then attempt to remove the listeners using the original function rather than the bound version.
Also, because binding returns a new function, if you bind a bound function you are in fact wrapping a function in a function, with another function. You should be aware of this because it affects performance and will prove trickier to manage in terms of avoiding memory leaks. My preferred approach to binding is to use closures with their own deconstruction methods (i.e. rely on self, but make sure you have methods to nullify it's content), but this does take more forward thinking and is not so relevant in smaller JS projects; or one off function bindings — especially if the bound method is never caught in any reference.
without self and bind?
It is also worth mentioning that sometimes you can achieve the same result without using bind at all, and instead use apply — which should be natively available in anything you may choose to use. The major difference being that nothing is wrapped up with the function, and calling apply actually executes the function there and then with a different context — the first argument passed to apply.
var externalMethod = function(){
console.log(this); // will output myObject when called below
};
var myObject = {
method2: function(){
externalMethod.apply(this);
}
};
What is this?
Just to elaborate this answer with further detail about this — before the recent comments get deleted. this will refer to one of four things, depending on how the function you are using it within was called:
myObject.method()
The above will have a this of myObject, unless method has had a .bind(context) operation applied. In which case this will be whatever the last bound context was.
unattachedFunction()
Will have a this of the global context (usually window in browser environments), unless unattachedFunction has had a .bind(context) operation applied. In which case this will be whatever the last bound context was.
anyFunction.apply(otherObject)
or
anyFunction.call(otherObject)
Both will always have a this of otherObject, because calling in this way will override any binding.
new myObject()
Will have a this that refers to a new instance of myObject, this will override any binding.
Simple thought experiment
Taking all the above into account, what would this be inside referencedMethod?
var referencedMethod = myObject.method;
referencedMethod();
Correct! it will be the global context. This is why if you want to share methods with other objects or code — but still retain the original owner as context — you really need to either bind, or keep the function bundled with its owner object so you can call or apply.
Self is used to make sure the original this is maintained within the object.
This comes in handy when using event handlers and so on.
You can read more about this here
The first answer covers it basically, also it shows a good link. Check it out.
It is used for reference purposes. this under Javascript behaves different than in other languages. For more details look at MDN Docs on this

How do you explain this structure in JavaScript?

(function()
{
//codehere
}
)();
What is special about this kind of syntax?
What does ()(); imply?
The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
function name (){...}
name();
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.
It's an anonymous function being called.
The purpose of that is to create a new scope from which local variables don't bleed out. For example:
var test = 1;
(function() {
var test = 2;
})();
test == 1 // true
One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.
The snippet below will cause an error:
var aVariable = 1
var myVariable = aVariable
(function() {/*...*/})()
Here's what it's actually doing:
var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();
Another way of creating a new block scope is to use the following syntax:
new function() {/*...*/}
The difference is that the former technique does not affect where the keyword "this" points to, whereas the second does.
Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.
That is a self executing anonymous function. The () at the end is actually calling the function.
A good book (I have read) that explains some usages of these types of syntax in Javascript is Object Oriented Javascript.
This usage is basically equivalent of a inner block in C. It prevents the variables defined inside the block to be visible outside. So it is a handy way of constructing a one off classes with private objects. Just don't forget return this; if you use it to build an object.
var Myobject=(function(){
var privatevalue=0;
function privatefunction()
{
}
this.publicvalue=1;
this.publicfunction=function()
{
privatevalue=1; //no worries about the execution context
}
return this;})(); //I tend to forget returning the instance
//if I don't write like this
See also Douglas Crockford's excellent "JavaScript: The Good Parts," available from O'Reilly, here:
http://oreilly.com/catalog/9780596517748/
... and on video at the YUIblog, here:
http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/
The stuff in the first set of brackets evaluates to a function. The second set of brackets then execute this function. So if you have something that want to run automagically onload, this how you'd cause it to load and execute.
John Resig explains self-executing anonymous functions here.

Categories

Resources