Good Morning everyone,
So I have a rather confusing question so I will try to be as clear as possible and keep it just as concise.
Assume that I have a function basicFunction. basicFunction has two arguments of funcWithParams and callback.
basicFunction(funcWithParams, callback){
.
.
.
// do stuff here
}
funcwIthParams is exactly what it says, a function either with or with out arguments, argument callback is a function that triggers when the initial part of basicFunction is completed.
With all that being said above, here is my question. Is it possible when passing a function with parameter to grab the function name itself, and each individual argument that was passed with it, and the value of each passed argument? I know for sure you can get a function name as a string, but I'm not exactly sure about the arguments and the values for each.
I have been researching this like crazy for the last three days, and I'm sure there is a way, but I have yet to find an answer.
Example
function basicFunction(funcWithParams, callback){
// create a loop to go through and log each of the parameters in the first argument's function
}
function somethingElse(param1, param2, param3){
}
function callbackFunction(){
alert("I did stuff");
}
basicFunction(somethingElse(param1, param2, param3), callbackFunction);
I think you're probably looking for something usually called partial application or currying (after the mathematician Haskell Curry).
JavaScript doesn't have pure currying (built in; it's easy to add), but does have Function#bind, which lets you create a function based on another function that, when called, will call the original function with a specific this value and with any arguments you give. If you don't care about this, just use null. As that's clear as mud, let's have an example:
function foo(a, b) {
snippet.log(a + ", " + b);
}
foo(1, 2); // "1, 2"
// Create curried version
var bar = foo.bind(null, 100);
// Call curried version
bar(200); // "100, 200"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
There, we "curried" the value 100 for the argument a when creating bar from foo.
So in your example, you'd do this:
basicFunction(somethingElse.bind(null, param1, param2, param3), callbackFunction);
Re your comment:
This is almost what I'm trying to do, but instead what I'm looking at is something like bar(foo(1,2), 100);, and from this getting the results of "foo" as a string, and the values of 1 and 2.
If you do bar(foo(1,2),100), foo gets called with the arguments 1 and 2, and then its return value is passed into bar along with 100. By the time bar is called, there is no information passed to it that in any way refers back to foo, 1, or 2. Exactly the way x = foo(1, 2) sets the return value of foo on x, again without anything continuing to refer back to foo (or 1 or 2) from x.
If you want access to the args, then the only thing that comes to mind is to pass an object with the function and its arguments, like this:
bar({f: foo, args: [1, 2]}, 100);
Then, in bar:
function bar(finfo, additionalArg) {
console.log(finfo.f.name); // "foo", probably, see caveats
console.log(finfo.args[0]); // 1
console.log(finfo.args[1]); // 2
// calling it
finfo.f.apply(null, finfo.args);
}
Function#apply calls the function you call it on, using the first argument you give it as the this value for the call, and then using the arguments you give it as an array as the individual arguments to pass the function.
Live Example:
function foo(a, b) {
snippet.log("foo called with " + a + " and " + b);
}
function bar(finfo, additionalArg) {
console.log(finfo.f.name); // "foo", probably, see caveats
console.log(finfo.args[0]); // 1
console.log(finfo.args[1]); // 2
// calling it
snippet.log("bar calling finfo.f via apply");
finfo.f.apply(null, finfo.args);
}
snippet.log("Calling bar");
bar({f: foo, args: [1, 2]}, 100);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Caveats:
Function#name was commonly provided by browsers, but wasn't part of the spec until June of this year when ECMAScript 6th Edition (ES6) came out. So you may find the odd browser that doesn't support it. If so, you may have to do the horrible toString thing to figure out the function's name.
Not all functions have names. ES6 gives many formerly-anonymous functions names, but it's still possible to create anonymous functions, and not all browsers will support the various ways ES6 infers function names (for instance, from expressions like var f = function() { };).
The only truly guaranteed way to provide a name for foo is to do it manually when creating the function:
function foo() {
//...
}
foo.name = "foo";
Soon that won't be true, but it is in today's world.
If you're working with an instance of a class, you may need to worry about context. In this case, it makes sense to bind. For instance:
function Sum() {
this._total = 0;
this.addTen = this.add.bind(this, 10);
}
Sum.prototype.add = function(amount) {
this._total += amount;
return this;
};
Sum.prototype.toString = function() {
return '' + this._total;
};
var sum = new Sum();
sum.addTen().addTen();
console.info(sum);
// 20
However, outside of an instance, there is usually no need for context and the more appropriate form of currying may be to create a factory function, like so:
function createAdder(amount1) {
return function AddTo(amount2) {
return amount1 + amount2;
};
}
var addTenTo = createAdder(10);
var fifty = addTenTo(40);
console.info(fifty);
// 50
This usually comes down to implementation details and preference. There are good uses and arguments for both methods.
Related
What I'm trying to say with the title is:
Is there a difference in:
argument = [arg1, arg2, arg3];
Foo.bar.apply(Foo, argument);
compared to:
Foo.bar(arg1, arg2, arg3);
Except the obvious (argument vs. non argument)?
What is the reason to use the two following different "calling" methods for the same method (bar)? I have understand that apply has to do with the calling object, but is there a difference in this case?
What is the difference between call and apply? gives a lot of info regarding apply, but I haven't found a good answer to why to pass "myself".
The longer story:
/* This is the bar method in CFoo class */
CFoo.prototype.bar = function(a,b,c) {
/*
* Magic things happen here,
* and also...
*/
if (a == "SomthingSpecial") {
this.bar(a,b);
}
}
Most of the place where bar is called it is via an global instance of CFoo.
/* In the begining... */
Foo = new CFoo();
/* Some other place */
Foo.bar("Test", 3, function(v) {
/* Some stuff */
});
/* And another place */
arr = ["Test2", 4, function(v) {
/* Other stuff */
}];
Foo.bar.apply(Foo, arr);
Edit: Explained the title a bit more. Answered in #nils answer comment.
The "and another place" code, where .apply() is used, apparently wants to use an existing array as the argument list for an invocation of the function. The only (easy) way to do that in JavaScript is with .apply.
In other words, the code has an array:
arr = ["Test2", 4, function(v) {
/* Other stuff */
}];
and wants to get the effect of
Foo.bar("Test2", 4, function(v) { ... });
That is, it wants to call Foo.bar() with the array elements as arguments. To do that, it can use .apply(), but in order to make sure that this is a reference to object Foo it passes Foo as the first parameter.
So there are two requirements that come together:
The function Foo.bar() is designed to work with a correctly-set value for this, so it must be invoked either as Foo.bar() or in some way such that Foo is used as the value of this;
For some reason, a list of arguments to be passed in to Foo.bar() has been generated or computed or whatever, and that list is in an array.
.apply() does two things:
The first argument changes the context (this) of the function call.
The second argument is an array that is applied to your function. So each value in your array will be an argument value when bar is called. That would lead to a=arr[0], b=arr[1], c=arr[2]
To demonstrate why you need to pass in Foo as your context, let's look at an example. If you were to call the following, it would fail, because this would equal null:
Foo.bar.apply(null, arr); // null instead of Foo
// in the function call...
if (a == "SomthingSpecial") {
this.bar(a,b); // this == null here
}
Alternative Approach (EcmaScript 2015)
If you can work with EcmaScript 2015 and want to avoid having to pass the context, you could use the spread operator instead:
Foo.bar(...arr); // Spreading the array with the spread operator
I'm very new to JS and I have been playing around with Jasmine.
In Jasmine, I can see a method called spyOn, which does inspect/spy the functions.
How does this works in js? Coming from Java background is it a proxy? How to write one?
You can find the precise implementation on GitHub, but here is a simplified explanation:
function mySpy(obj, methodName) {
// remember the original method
var originalMethod = obj[methodName];
// ... then replace it with a method that ...
obj[methodName] = function () {
// ... does whatever additional thing it wants to do ...
console.log(methodName + " called, first argument: " + arguments[0]);
// ... and then calls the original method with the same arguments,
// and returns the result.
return originalMethod.apply(this, arguments);
};
}
Now you can do this:
var o = {
inc: function (x) { return x + 1; }
};
mySpy(o, "inc");
console.log(o.inc(13));
This will output
inc called, first argument: 13
14
Three important things for you to know, coming from a Java background, are
In JavaScript, it is not a problem to change an object's methods after the fact, dynamically. Calling someObj.someMethod = someOtherFunction is perfectly valid. (To be 100% precise, you may not actually be overwriting the original method, because it may be somewhere up the prototype chain, instead of on the object itself. That's an advanced topic though, and not very important here. Also, Java's distinction beween methods and class members doesn't apply to JavaScript.)
The special "variable" arguments inside a function contains whatever arguments the function was called with. In Java terms, imagine that someMethod(Foo x1, Bar x2) always has an implicit second signature of the type someMethod(Object... arguments), meaning you could always use x1 and arguments[0] interchangeably.
obj.someName and obj["someName"] are entirely equivalent in JavaScript. Because of this, you can easily access/change an object's properties using the property name as a string, something that in Java you would have to use reflection for.
I am stumbling upon a problem that I have seen before, but that I couldn't solve before. I will likely stumble upon it again in the future, so please, someone explain it to me what is going on?
In the partial snippet of javascript below, I have a function that populates a screen, including an order combobox (twitter bootstrap). When I click on one of the order items in that combobox, it should invoke the function clsModCampaigns.blnCompaniesListReload().
For a reason that I don't understand, once inside the '$.each' iterator, the global object reference 'objModCampaigns' is lost? I get a successful alert '1', but not an alert '2'.
Within the $.each, I would like to use 'objModCampaigns.arrOrderBy' instead of 'this.arrOrderBy', but the $.each iterator only seems to work this way. Why is it working this way??
What is going on with 'this', or with variables/objects assigned in the root of the class with 'this'?
Is $.each just special??
function clsModCampaigns(objSetSystem, objSetModuleBase)
{
objModCampaigns = this;
arrOrderBy = {
intID: 'ID',
strName: 'Name'};
[...]
this.blnScreenCampaignInitialize = function (fncSuccess,fncError, intID) {
$.each(this.arrOrderBy, function (strFieldName, strFieldDescription) {
if(strFieldName != 'datDeleted' || objSystem.blnHasPerm("CAMPAIGNS_DELETED")) {
strOrderByID = "ulCampaignsCompaniesListOrderBy" + strFieldName;
$("#ulCampaignsCompaniesListOrderBy").append('<li>'+strFieldDescription+'</li>');
$("#"+strOrderByID).unbind("click").bind("click", function() {
alert("1");
objModCampaigns.arrCurrentShownCompanies.strOrderBy = strFieldName;
objModCampaigns.blnCompaniesListReload();
alert("2");
});
}
});
return true;
};
}
The code you have is
$.each(this.arrOrderBy, ...);
You want
$.each(arrOrderBy, ...);
The reason for it is the this context on that line is different because it is inside a new function this.blnScreenCampaignInitialize.
This is just a part of how JavaScript works
var message = "hello";
function welcome() {
console.log(message);
}
welcome(); // "hello"
P.S. use var
If you don't use var, you'll be attaching all of your vars to the global object.
function hello() {
foo = "bar";
console.log(foo);
};
hello(); // "bar"
console.log(foo); // "bar"
// Holy smokes! `foo` has escaped our `hello` function!
Compare that to
function hello() {
var foo = "bar";
console.log(foo);
}
hello(); // "bar"
console.log(foo); // ReferenceError: foo is not defined
// much better
Now let's see a terrible example
function a() {
b = 5;
return b;
}
function b() {
return "function";
}
console.log(a()); // 5
console.log(b()); // TypeError: number is not a function
This is happening because we didn't use var properly. We first define b as a function but after running a(), b is now set to 5. The second log statement is the equivalent of trying to run 5() because b is no longer a function.
P.P.S. it's pretty unconventional to prefix your vars with str, int, fnc, obj, or cls in JavaScript.
I understand you're a "VB guy" according to your comments, but that's no excuse for bringing your own conventions to the language. I see in your profile that you're fluent in Dutch, English, German, and French. I would recommend you treat learning programming languages much the same as spoken languages: each of them have their own explicit set of rules and conventions.
Here's a heap of free JavaScript books for you. I hope they can help you learn some more basics.
P.P.P.S. Overall, your function is really big as it is, and I can see you already truncated some of the code with your [...]. The whole thing could probably benefit from some better composition.
If you paste all of your code, maybe someone could help you better.
What is going on inside the $.each() ?
Regarding you question title, I'm trying to answer:
// each function in source
function (obj, callback, args) {
//...
}
Check the source of complete $.each function by yourself, you can see any function's source code just by typing the function name in the appropriate text box (the second on top).
Here in each function, the array/object passed in to the each function (the first argument) is being run through a loop and each value is being passed in to the callback (second argument) and that call back is getting executed like:
callback.apply(obj[i], args);
So, the passed callback in the each function is being executed each time the loop occurs ad the current value in the loop is passed as the argument of callback function along with the third argument args.
If your function function clsModCampaigns(){ //... } is a normal function then this inside this function points to global window object. so just use:
$.each(arrOrderBy, ...);
instead of
$.each(this.arrOrderBy, ...);
Because, arrOrderBy is within the direct scope so arrOrderBy is accessible directrly. For example:
function someThing()
{
var x = 'y'; //<-- this scope (everything inside someThing) is
// global for somethingElse inner function
function someThingElse)(x) //<-- possible to use directly
{
}
}
The keyword this behaves differently depending on the context. Check about this on MDN.
I just started programming and I've been playing around with it. I watched a programming course on lynda.com to start out, but it didn't cover functions very well, I know what they are, but I don't know the different formats of functions or how to call them. I know how to call simple things like this:
var foo=function {
//code...
}
but I want to use more complicated things like this (I'm starting to to things with HTML):
$(document).keypress(function(e)) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
or just whatever other styles there are.
There are no different formats of functions. All of them are defined with function keyword followed by arguments and body. If you have a function foo then you call it via foo(); (you can pass arguments as well, foo(1,2,3);). There are more complex ways of calling functions, for example via foo.call or foo.apply but I don't think it is necessary to talk about that here.
Note that functions in JavaScript are first class citizens. That means that they can be treated as objects. In particual you can pass them to another function. Have a look at this example:
var foo = function(fn) {
return fn()+1;
};
What happens here? foo takes a function as an argument (we know that because fn() is called in body), calls it and adds 1 to result. So if I call foo like this:
foo(function() {
return 1;
});
what would the result be? That's a simple example. Consider something more complex:
var foo = function(list, fn) {
var res = [];
for (var i = 0; i < list.length; i++) {
var mapped = fn(list[i]);
res.push(mapped);
}
return res;
};
This is a simple version of the .map method on lists. So it takes a list and a function as arguments, then applies the function to each element of the list and returns a new list:
> foo([1, 2, 3], function(el) { return -el; });
[-1, -2, -3]
It is the same as calling
> [1, 2, 3].map(function(el) { return -el; });
[-1, -2, -3]
Different ways of declaring functions
function A() {}; // function declaration
var B = function() {}; // function expression
var C = ( function() {} ); // function expression with grouping operators
var D = function foo() {}; // named function expression
var E = ( function() { // immediately-invoke function expression (IIFE) that returns a function
return function() {}
})();
var F = new Function(); // Function constructor
var G = new function() {}; // special case: object constructor
Your code is actually a good example of the different types of functions. First is $(), which represents the JQuery library--a useful add-on to JavaScript. You typically give it a string called a CSS selector, which is a way to pick out a part (or parts) of a document. In this case, you're picking out the whole document, but you could also say something like $("#logo"), which will return a document with id="logo" or $("img") will return all elements in the document.
An object in JS can be just about anything, and there are different types of objects. Each type of object has special functions available to it. These functions are called methods.
In the above example, the document object returned by $(document) has the .keypress() method available to it, which listens for a particular keypress. Keypress needs to know what to do when a key is pressed, and you do so by giving it a function as a parameter. That function will execute every time a key is pressed.
One thing that's useful to remember about JavaScript is that functions are thought of as "first-class citizens", meaning they are as good as straight-up values as far as JavaScript is concerned. So if I have a function like:
var myString = function(word)
{
return word;
}
If I do:
var myWord = "hello";
It's the same as:
var otherWord = myString("hello");
If I compare them:
var compareWords = function(word1, word2)
{
return word1 == word2;
}
var compareMyWords = compareWords(myWord, otherWord);
It's the same as saying
var compareMyWords = true;
This is important to know because it means functions can take other functions as arguments without a problem. We see that happening in the keypress method. It might be a bit hard to notice, but you can see it if you declare the function beforehand:
var keypressFunction = function(e)) {
if(e.which == 13) {
alert('You pressed enter!');
}
The following is the same as your example:
$(document).keypress(keypressFunction);
The difference is that your example uses an anonymous function. It hasn't been declared with "var" or "function", so I couldn't reuse it if I wanted to. That's not really a bad thing. Anonymous functions are very useful when you get into more advanced stuff.
Your anonymous function is allowed one parameter, an object representing the key that was actually pressed. In this case it only wants to do something if the key represented by 13 is pressed (Enter).
Finally there's the alert function, which pops up a message. Note that functions don't always have to return a value. Usually when they don't, they do something to their environment instead (otherwise what's the point). In your example only one function actually returns something--the $() function, although nothing gets done with it, but you could keep going and replace the semicolon at the end with a period and use the ready() method or whatever methods are available to the object returned by $(document). In fact, as long as you know what type of object is being returned, you could do something like:
$("#message").addClass("alert").fadeIn().delay().fadeOut();
Because each of these methods return the same object, we can do this "method chaining". jQuery purposely tries to make most of its methods return the DOM objects it acted on so that you can do this. Other libraries, like d3.js, make use of method chaining for some very cool visual transformations.
I don't think starting off using jQuery is as horrible an idea as others might advise. It's still JavaScript. It could be argued that JQuery forces you to learn advanced concepts (callbacks, CSS selectors, etc) that you could otherwise hobble by for years without knowing. I could also argue that JavaScript itself is a bad language to start with when learning to program.
Instead I'll say dive in and have fun! The ultimate purpose is to build awesome things & not get too crippled by having to do it the right way. Find a good balance between learning and building, and don't get too discouraged by the few jealous stackoverflow users who come here to snuff the joy they once had in building awesome things.
I order to know how to call different types of functions in Javascript it is important to know all JavaScript Function types. Below is a link that take you to:
All JavaScript Function Types?
I personally think you are over complicating it.
Yes, the different ways of writing a function tend to have different names (function, anonymous function, colosure, lambda,....) but in the end its all a function:
They combine several statements into one.
For example:
// Crating a function (most commomn way)
function a() {
alert('a');
};
// Creating a anonymous (nameless) function and assigning it to b
var b = function() {
alert('b');
};
var c = a;
var d = b;
var e = {};
// Creating a function that accepts a function and executes it.
// This is in essence what $(document).keypress() does
e.f = function(f){
f();
};
// Alerts: a
a();
// Alerts: b
b();
// Alerts: a
c();
// Alerts: b
d();
// Sample how you can call $(document).keypress()
// Alerts: c
e.f( function() {
alert('c');
});
// Alerts: a
e.f(a);
// Alerts: b
e.f(b);
I've been through a ton of posts and I finally got what I needed thanks to this:
$("a.foo").click(function(){
var that = this;
jPrompt("Type something:","","", function(r) {
$(that).text(r);
}
}
From the following:
Accessing $(this) within a callback function
I was wondering if someone could expand on what exactly is happening here (why is this not available without re-assigning?) and what core information I should read up on? From what I gather this might have something to do with closures... that's most of what I bumped into while searching around. Is that accurate?
In my case, I was looking to execute some code, then redirect once an ajax request completed. In the callback function I was running $(this).attr("href") which was returning undefined.
this is assigned by javascript according to how a function is called. So, it is the jPrompt() function that determines what value this will have in your callback when jPrompt() calls the callback.
So, unless jPrompt goes out of its way to keep the same value for this via some argument you passed in, it will likely have a different value. As such, you can save it away for access within the callback as you've done. This is a very common design pattern in javacscript callbacks.
FYI, some of the ways that this is assigned:
obj.method() - this in method() will be set to obj
func.call(obj) - this in func() will be set to obj
func() - this will be set to window in func() or undefined in strict mode
The meaning of this changes depending on where you're at. The this within a handler for your click event means something other than the this within the callback passed to your jPrompt function.
For what it's worth, you don't need to re-assign this, since the event object passed into your handler will have a reference to the currentTarget:
$("a.foo").on("click", function (event) {
// 'this' here refers to the anchor we clicked
jPrompt("Type something:", "", "", function (r) {
// 'this' here refers to whatever jPrompt instructs
$(event.currentTarget).text(r);
}
}
The code in the question with some added comments:
$("a.foo").click(function(){
var that = this; //`this` holds the a object clicked. now so does `that`!
jPrompt("Type something:","","", function(r) {
//even if `this` has a different value here, `that` still holds the a object clicked
$(that).text(r);
}
}
This is something you will often find yourself doing in similar situations. this is context-dependent and you often need to keep the value this had in one context and use it in another.
A quote from the ECMAScript specification:
10.1.7 This
There is a this value associated with
every active execution context. The
this value depends on the caller and
the type of code being executed and is
determined when control enters the
execution context.
Hope that answers your question. You also asked for a resource for further reading. Please visit:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this
These guys provide excellent documentation both detailed and typically quite accurate (unlike other popular sources of reference that often comes first in Google searches -- w3cshools.com I am thinking of you!).
A Short Overview of this
this in JavaScript is dynamically scoped. Its behavior differs from all other variables which are lexically scoped. Other variables don't have a different binding depending on how the function is called; their scope comes from where they appear in the script. this however behaves differently, and can have a different binding depending not on where it appears in the script but on how it's called. Consequently, it can be a source of confusion for people learning the language, but mastering it is necessary in order to become a proficient JavaScript developer.
Since this is dynamically bound there are several ways to change its values based on how you call the function.
Examples
When you execute a function in JavaScript, the default this is window.
function foo() {
console.log(this);
}
foo(); // => window
The this value can be changed in a number of ways. One way is to call the function as a method of an object:
var x = {
foo: function() {
console.log(this);
}
};
x.foo(); // => This time it's the x object.
Another way is to use call or apply to tell the function to execute in the context of a certain object.
function foo() {
console.log(this);
}
foo.call(x); // => x object again
foo.apply(x); // => x object as well
If you call or apply on null or undefined, the default behavior will occur again: the function will be executed in the context of window:
function foo() {
console.log(this);
}
foo.call(null); // => window
foo.apply(undefined); // => window
However, note that in ECMAScript 5 strict mode, this does not default to window:
(function() {
'use strict';
function foo() {
console.log(this);
}
foo(); // => undefined
foo.call(null); // => null
foo.apply(undefined); // => undefined
})();
You can also set the this by using bind to bind the function to an object before it is called:
function foo() {
console.log(this);
}
var bar = {
baz: 'some property'
};
var foobar = foo.bind(bar);
foobar(); // => calls foo with bar as this
Going Father: Lazy Bind / Uncurrying this
Going further, you may sometimes want to take functions which act on a this and allow the this value to be passed in as the first argument to the function. This can be really helpful for Array methods, such as forEach. For instance, let's say you are dealing with an object which is array-like but not actually an array.
var arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
'length': 3
};
If you want to iterate over this object with forEach, you could use call:
Array.prototype.forEach.call(arrayLike, function(item) {
console.log(item);
});
// Logs: a, b, c
However, another option is to create a forEach function which can be called directly on your object:
var forEach = Function.prototype.call.bind(Array.prototype.forEach);
Now you can use this function anytime you want to iterate over an array-like object:
forEach(arrayLike, function(item) {
console.log(item);
});
// Logs: a, b, c
Sometimes this method is referred to as "uncurrying this". However, I prefer to create a function which can generate these "uncurried" functions and call it "lazy binding".
var lazyBind = Function.prototype.bind.bind(Function.prototype.call);
var forEach = lazyBind(Array.prototype.forEach);
var slice = lazyBind(Array.prototype.slice);
var map = lazyBind(Array.prototype.map);
forEach(arrayLike, function(u) {
console.log(u);
});
// Logs: a, b, c
var realArray = slice(arrayLike);
// Converts arrayLike into a real array
forEach(
map(arrayLike, function(u) {
return u + 'Q';
}),
function(u) {
console.log(u);
}
);
// Logs: aQ, bQ, cQ
One really awesome thing about this technique is it can be useful for creating securable JavaScript, which can be helpful if you don't want other scripts on the page snooping around your internal variables. This is a pretty advanced meta-programming technique, though, and you don't see it in day-to-day JavaScript.