JavaScript Patterns: Context of Function Call - javascript

I have a ton of JavaScript from the dawn of time with function calls written like this:
THING.someFunction.call(THING);
It seems to me that should always be equivalent to:
THING.someFunction();
Are these two calls always equivalent? What about old versions of JavaScript?
It seems to me the purpose of the second THING in that first line of code is to set the context (this) inside someFunction. But the context inside that function should already be THING by default, right?
Just to be clear, THING is defined something like this:
var THING = function () {
// private vars
return{
// code
someFunction : function () {
// code
}
};
}();

Yes, they are equivalent. And I don't know any version of JavaScript in which they were not (however, call seems to have been added in 1.3).

They are the same technically. But they also behave slightly different in asynchronous programming. call() is used to call a function by passing a scope as the parameter. This provides a convenient way to call defined functions in callbacks and delayed execution (setTimeout, setInterval). If you have used any of the JS libraries, you would have noticed $.proxy, or _.bind, these are aliases that implement call(scope);
See this MDN doc for more info.

Related

What is the difference between (function(){/*.....*/})(); and (function($){/*.....*/})(jQuery);

Is there difference between :
(function() {
/*..........*/
})();
and :
(function($) {
/*..........*/
})(jQuery);
Other people explained what the difference is, but not why you use the latter.
The $ variable is most often used by jQuery. If you have one script tag that loads jQuery and another that loads your code, it's perfectly fine. Now throw prototype.js into the mix. If you load prototype.js and then jQuery, $ will still be jQuery. Do it the other way around and now $ is prototype.js.
If you tried to use $ on such a page, you'd likely get errors or weird behavior.
There are many questions on StackOverflow about this problem. Plugins shouldn't assume much about the page they're loaded in, so they use this pattern defensively.
i am asking if there is difference between (function(){/…/})(); and (function($){/…/})(jQuery);
A little difference. In case of (function($){/*…*/})(jQuery); and absense of jQuery you'll get an error message immeditally after page loads. It's a simpler to detect jquery absense or incorrect order of scripts inclusion, when jquery-based code included before jQuery.
In case of (function(){/*…*/})(); you'll get an error message when code inside this construction actually call one of jQuery methods. It's harder to detect this error, but on the other side you can include your jquery-based scripts before jquery.
I prefer first case.
The second form, (function($){/*…*/})(jQuery); can be slightly safer when working in an environment where you don't (or can't) strictly enforce what code gets put on your site.
I used to work on a large site with a lot of third-party ads. These ads would often unsafely inject their own version of jQuery and occasionally they would override jQuery's global $ object. So, depending on how we wrote our code, we might be calling methods that no longer existed or had slightly different behaviour from what we expected. This could be impossible to debug, since some ads would never appear in our area or were excluded from our environment. This meant we had to be extremely protective of scope, inject our dependencies before any ad code had a chance to load, namespace anything that had to be global and pray no ad screwed with us.
Other answers are quite fragmented so I'd like to give a more detailed answer for the question.
The main question can be self-answered if you understand..
What does (function(argument){ /*...*/ })(value); mean?
It's a quick hand version of:
var tempFunction = function(argument){
/* ... */
}
tempFunction(value);
Without having to go through the hassle of conjuring up a new terrible name for a function that you will only call once and forget. Such functions are called anonymous functions since they aren't given a name.
So (function(){/*...*/})() is creating a function that accept no argument and execute it immediately, while (function($){/*...*/})(jQuery) is creating a function that accept one argument named $, and give it the value of jQuery.
Now that we know what the expression means, surely the first think on our mind is
"Why?". Isn't $ jQuery already?
Well, not exactly. We can never be sure. $ is an alias of jQuery, but other libraries can also use the same alias. As user #FakeRainBrigand already pointed out in his answer, prototype.js also use $ as its alias. In such cases, whichever library assigns its value to $ later wins out.
The practice of (function($){...})(jQuery) is very similar to an alias import in other programing languages. You are explicitly telling the system that your function:
Requires an object/library named jQuery, and
Within your function, $ means jQuery.
So even when someone include a new library later that override the alias $ at the global level, your plugin/framework still works as intended.
Because javascript is so... "flexible" in variable assignment, some people (including me) go as far as doing things like
var myApplication = (function($, undefined){ ... })(jQuery);
Apply the same understanding, it is easy to interpret the second argument part as: assign nothing to the variable undefined. So we can be sure that even if some idiot assigned a value to undefined later, our if(checkVariable === undefined){} won't break. (it's not a myth, people really do assign values to undefined)
When is it commonly used in javascript?
This anonymous function practice is most commonly found in the process of providing encapsulation for your plugin/library.
For example:
var jQuery = (function(){
var publicFunction = function(){ /* ... */}
var privateFunction = function(){ /* ... */}
return {
publicFunction : publicFunction
}
})();
With this, only jQuery.publicFunction() is exposed at the global scope, and privateFunction() remains private.
But of course, it is also used any time you simply want to create a function, call it immediately, and throw it away. (For example as a callback for an asynchronous function)
For the bonus question
why they used (function(){}() twice in the below code?
Well, most likely because they don't know what they're doing. I can't think of any reason to put nested function in like that. None at all.
(function(){/*...*/})(); does not set $ as reference to jQuery within IIFE and (function($){/*...*/})(jQuery); sets $ or other parameter name; e.g.; (function(Z){/*...* Z("body") where Z : jQuery*/})(jQuery); as reference to jQuery within IIFE
The they are both closures. The first is just an anonymous function that will fire any well formatted code that is inside immediately. The second is the jQuery closure. It is how the jQuery library initiates it wraps its code in the JQuery object and exposes it isn't the $ symbol.
(function(){}()) // this is a closure
(function($){}(jQuery)) // is a closure that wraps the executed code inside of the jQuery returned object and exposes it via the $.
With this (function(){/*…*/})();, you are not passing any argument to the inner function, while with this (function($){/*…*/})(jQuery); you are passing jQuery as argument to the inner function and expecting its value as $(which means, you will be able to use jQuery inside the inner function).
Ex:
(function($){
$(document).ready(function() {
console.log('all resources loaded');
})
})(jQuery);
They both are examples of Immediately Invoked Function Expression. In that sense, there is no difference between (function(){/*…*/})(); and (function($){/*…*/})(jQuery);. So no benefits are gained by wrapping (function($){/*…*/})(jQuery); inside (function(){/*…*/})();
A new execution context is created when a function is executed. So when (function(){/*…*/})(); is executed a context is created. Again when (function($){/*…*/})(jQuery); is executed, another context is created. Since the first context is not used (i.e. no variables are declared inside it), I don't see any advantages gained by the wrapping.
(function() { // <-- execution context which is not used
(function($) { // <-- another execution context
"use strict";
/*..........*/
})(jQuery);
})();

why is it necessary to wrap function call in a function body

I often see something like the following in JavaScript:
$("#sendButton").click(function() {
sendForm();
}
Why is it necessary to wrap the call to sendForm() inside a function? I would think that doing it like this would be more readable and less typing.
$("#sendButton").click(sendForm);
What are the advantages/disadvantages to each approach? thanks!
There's typically two cases where you'd want to use the former over the latter:
If you need to do any post-processing to the arguments before calling your function.
If you're calling a method on an object, the scope (this reference) will be different if you use the second form
For example:
MyClass = function(){
this.baz = 1;
};
MyClass.prototype.handle = function(){
console.log(this.baz);
};
var o = new MyClass();
$('#foo').click(o.handle);
$('#foo').click(function(){
o.handle();
});
Console output:
undefined
1
Probably one too many answers by now, but the difference between the two is the value of this, namely the scope, entering sendForm. (Also different will be the arguments.) Let me explain.
According to the JavaScript specification, calling a function like this: sendForm(); invokes the function with no context object. This is a JavaScript given.
However, when you pass a function as an argument, like this: $(...).click(sendForm), you simply pass a reference to the function for later invocation. You are not invoking that function just yet, but simply passing it around just like an object reference. You only invoke functions if the () follows them (with the exception of call and apply, discussed later). In any case, if and when someone eventually calls this function, that someone can choose what scope to call the function with.
In our case, that someone is jQuery. When you pass your function into $(...).click(), jQuery will later invoke the function and set the scope (this) to the HTML element target of the click event. You can try it: $(...).click(function() { alert(this); });, will get you a string representing a HTML element.
So if you give jQuery a reference to an anonymous function that says sendForm(), jQuery will set the scope when calling that function, and that function will then call sendForm without scope. In essence, it will clear the this. Try it: $(...).click(function() { (function() { alert(this); })(); });. Here, we have an anonymous function calling an anonymous function. We need the parentheses around the inner anonymous function so that the () applies to the function.
If instead you give jQuery a reference to the named function sendForm, jQuery will invoke this function directly and give it the scope that it promises to always give.
So the answer to your question becomes more obvious now: if you need this to point to the element target of the click when you start work in sendForm, use .click(sendForm). Otherwise, both work just as well. You probably don't need this, so skip the anonymous function.
For those curious, scope can be forced by using the JavaScript standard apply or call (see this for differences between the two). Scope is also assigned when using the dot operator, like in: obj.func, which asks of JavaScript to call a function with this pointing to obj. (So in theory you could force obj to be the scope when calling a function by doing something like: obj.foo = (reference to function); obj.foo(); delete obj.foo; but this is a pretty ugly way of using apply.
Function apply, used by jQuery to call your click handler with scope, can also force arguments on the function call, and in fact jQuery does pass arguments to its click handlers. Therefore, there is another difference between the two cases: arguments, not only scope, get lost when you call sendForm from an anonymous function and pass no parameters.
Here you are defining an anonymous event handler that could call multiple functions inline. It's dirty and tough to debug, but people do it because they are lazy and they can.
It would also work like your second example (how I define event handlers):
$("#sendButton").click(sendForm)
Something you get by defining your event handlers inline is the ability to pass event data to multiple functions and you get this scoped to the event object:
$("#sendButton").click(function(event) {
sendForm();
doSomethingElse(event);
andAnotherThing(event);
// say #sendButton is an image or has some data attributes
var myButtonSrc = $(this).attr("src");
var myData = $(this).data("someData");
});
If all you are doing is calling sendForm, then there isn't much difference, in the end, between the two examples you included.
$("#sendButton").click(function(event) {
if(event.someProperty) { /* ... */ }
else { sendForm({data: event.target, important: 'yes'}); }
}
However, in the above case, we could handle arguments passed to the callback from click(), but if the sendForm function is already equipped to handle this, then there's no reason why you wouldn't place sendForm as the callback argument if that is truly all you are doing.
function sendForm(event) {
// Do something meaningful here.
}
$("#sendButton").click(sendForm);
Note that it is up to you where you handle the differing layers of logic in your program; you may have encapsulated certain generic functionality in a sendForm function then have a sendFormCallback which you pass to these sorts of function which handle the interim business of event/callback processing before calling sendForm itself.
If you are working in a callback-heavy environment, it would be wise to separate significant functionality from the callback triggers themselves to avoid callback hell and promote maintainability and readability in your source code.
It's just to lock scope. When you wrap that sendForm() in the anonymous function that closes over the current scope. In other words, the this will be kept with it. If you just pass sendForm then any calls to this will come from the calling scope.
This is a good question for learning about scope in javascript, and questioning conventions.
Nope, that second example is perfectly valid.
99.9% of jQuery examples use the first notation, that doesn't mean you need to forget basic JavaScript syntax.

What javascript coding style is this?

I am working on maintaining a ASP.NET MVC application that has the following coding style. The view has:
<script type="text/javascript">
$(document).ready(function() {
SAVECUSTOMERS.init();
});
</script>
There is a js file included that goes along these lines:
var SAVECUSTOMERS = (function() {
init = function () {
$("#saveCust").bind("click", OnSave);
$("#cancel").bind("click", OnCancel);
},
OnSave= function() {
//Save Logic;
},
OnCancel = function() {
//Cancel logic;
}
return { init: init };
})();
Is this a best practices JS coding style? Is the intent to have non obtrusive JS?
What is the SAVECUSTOMERS? I understand that there are different ways of creating classes in javascript (per this link), but this style does not fall into any of those categories listed
Where can I find more information on this style of JS coding?
1) Using a $(document).ready (or similar function from another library) function is considered standard practice in JavaScript. First of all, it ensures your JavaScript executes on page that has finished evaluating/building it's DOM. And it also abstracts away some of the browser-implementation inconsistencies when identifying when the DOM is in fact ready. But I assume you are mainly referring to the 2nd code block.
What you see there is that SAVECUSTOMERS is assigned the result of a self-executing an anonymous function. This is done for a few reasons, the most common being the ability to control the scope and 'namespace' of the functions and data inside the anonymous function. This is because JavaScript has lexical scope, and not block level scope.
The practice of using these self-invoking functions in JavaScript is very common
However the code itself has several problems. The variables init, OnSave and OnCancel are declared as global variables (because the var keyword was omitted). This largely defeats the purpose of wrapping them in an self-invoking function. Furthermore, the contents of that function are using a mix of object assignment syntax and standard expression syntax, which will result in syntax errors.
Also, by returning only the init function, the onSave and onCancel functions have been effectively 'hidden' or made 'private' through the use of closures. This helps keep namespaces clean and encapsulated.
If I were writing this code (some personal perferences here, there are a few ways to accomplish something simliar), then it would look like this:
var SaveCustomers = (function($) {
var init = function () {
$("#saveCust").bind("click", onSave);
$("#cancel").bind("click", onCancel);
};
var onSave = function() {
//Save Logic;
};
var onCancel = function() {
//Cancel logic;
}
return { init: init };
})(jQuery);
Some notes on the above:
I declare variables using the var keyword. This keeps their scope local to this function (you could also technically use named functions declarations as well)
I pass jQuery as the parameter in the self-invoking function, and assign it to $ as the argument in the function call. This protects the $ variable inside the function so that we know it references jQuery, and hasn't been munged by a secondary library that also uses $.
2) SAVECUSTOMERS is a basic JavaScript object, which has a single owned property called 'init', whose value is a function, as defined by the init declaration inside the execution.
3) Not sure about how to answer this question - your best bet for understanding JavaScript best practices is to read through other JavaScript code that is known to be of quality, such as the jQuery source, or Prototype, or Underscore, etc.
this style is known as jquery ... have you checked the JQuery website, go through it ...
This is called self-invoking functions in javascript. One of the articles I am giving below. you can get more on google.
http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/
If you are referring to the $ programming, then its related to JQuery which other answers have provided links too.
It's using the JQuery library.
JQuery includes a function called $(), which allows you to select elements from the DOM using a CSS-like syntax.
The $(document).ready bit is a standard JQuery method for making sure that the enclosed code only gets run after the page has finished loading. This is required to ensure that events get correctly attached to the relevant DOM objects.
The bit with functions being used as arguments for others functions is known as a 'closure' it's a very common way of writing Javascript, but in particular when using JQuery, which goes out of its way to make things easy to do and minimal code with this coding style.
See this page: http://blog.morrisjohns.com/javascript_closures_for_dummies for a beginners discussion of how closures work in Javascript and how to write them (note that this page doesn't look at JQuery at all; closures are a Javascript feature that is used heavily by JQuery, but you don't need JQuery to write closures)
This is a normal way to use jQuery for handling events.
What basicly happens is that you check that the document is loaded hence
$(document).ready(function() {
SAVECUSTOMERS.init();
});
And when it is you start to add your bindings to buttons or what ever they might be.
The intent of the code in SAVECUSOMTERS is to mimic private and public properties in objects. Since JS does not support these by default, this self invoking function executes and returns a certain number of properties. In this case it returns the 'init' method. Despite the fact that you see OnSave and OnClick, you'll find that you can't access them at all. They are "private" and only used internally within that function.
The $() function is part of a javascript library called jQuery http://jquery.com It's a pretty well rounded library and primarily is used for DOM manipulation.
The $(document).ready() function is a way for jQuery to continuously poll the page until it is loaded. When it is, the javascript within is executed.
The goal is to have public and private functions. OnSave and OnCancel are private functions that are only accessible within the scope of the self-executing anonymous (function() { ... } ()) which returns an object that gives access to the init function publicly.
SAVECUSTOMERS becomes the object returned by the above mentioned function, i.e. { init: init }, an object with one method init that has access to the functions within that closure.
You can read Douglas Crockford's Javascript: The Good Parts or Stoyan Stefanov's Javascript Patterns
Other notes:
The $() functions belong to the jQuery library
There are syntax errors because the functions should be separated by ; not , since they are within a function, not an object.

Naming: createFunctionDelegate() vs createDelegateFunction()?

It appears that I am not able to choose between two names for a function:
createFunctionDelegate() and createDelegateFunction().
If it matters, the purpose of the function is that it creates a new function that calls the supplied callback function in the context of the second argument. For example:
var foo = {
init: function() {
setTimeout(App.createFunctionDelegate(this.method, this));
},
method: function() {}
}
When foo.init() is run, it sets a timeout that calls a function which delegates the execution to another function (this.method) called in the context of this (foo).
Anyway, I am not sure which way I should name this function. This is important to me, because I am going to use it in hundreds of places and sometimes I type the one and occasionally the other one. This has to change, I have to choose.
I would use neither of these. What you want to do will be offered by bind() in ES5. I would define Function.prototype.bind if it does not exist already, as described here (but read the description and the possible drawbacks carfully).
This way you make sure you use native functionality if it is supported.
What about just createDelegate(this.method, this)?
As a side note, other places where I've seen this kind of method (and written them), the param ordering is context, function, so createDelegate(this, this.method)

Best approach to avoid javascript's “this” mistakes in XBL

Talking about XBL is not exactly talking about javascript. So I'll create this question that's related to this one, but now about XBL, where I'm not the creator of the root javascript code, but just of the methods and event handlers inside the bindings.
--
In some cases, the this keyword may not refer to the object I expect it to. (recent example: in an key event, in my XBL)
What's the best approach to avoid this kind of mistake?
For now, I'm using always the getElementById (or $.fn from jQuery), but I'm not sure if it's the best approach.
--update
A little bit more details:
Within a XBL method the only way to access the element that was defined in the Xul file (the GUI description file) without using "this" (as it may not be the "this" I expect) is with getElementById, and this makes the code not reusable, so I'm looking for alternatives..
As you've heard elsewhere, the problem is that the this parameter isn't necessarily the object you first thought of, especially when you're talking about event handlers and the like. The best way I found is to write a small function that will bind some object as the this variable and return another function that uses the binding to call the original function.
Take a look at this code:
var bindFunction = function(self, f) {
return function() {
return f.apply(self);
};
};
var foo = function() {
alert(this.hello);
};
var bar = {
hello: "Hello there"
};
var boundFoo = bindFunction(bar, foo);
boundFoo();
What I have is a function called bindFunction that takes an object (called self) and some function, and returns another function that will call the passed-in function applying the self object as the this variable.
The rest of the code is just some test code: a foo function that will alert this.hello, a bar object with a hello member, and how you can bind foo with bar.
In essence, I've taken a function that accepts no parameters and generated another function that will ensure the first is always called with the correct this variable. Ideal for event handlers.
(Sorry, but I know nothing about XBL, so I hope this will be of use.)
If there's not a best answer, a good approach could be use javascript files instead of XBL for the implementation. Looking the Xulrunner source code, looks like most code does this.
But I still would like to use XBL, if there was a way to work fine with it..

Categories

Resources