I am working my way through Eloquent Javascript and I came across a code snippet that looks like this:
function greaterThan(x) {
return function(y) {
return y > x;
};
}
var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));
Is there any real use-case to defining the function like this with an anonymous function inside of it? Wouldn't it be much simpler to do this:
function greaterThan(x,y){
return x > y;
}
var greaterThanTen = greaterThan(9, 10);
any ideas/comments/suggestions would be very helpful.
This is an example of a "closure". Basically, a call to greaterThan() gives you a function. That function, instead of just a mere function, carries with it the value of x - it's like embedding the value of x permanently into the function.
function obj(x) {
//"public interface"
//only these are exposed (inc and getX). x is private.
return {
inc: function() {
return ++x;
},
getX: function() { //a getter function to retrieve private x
return x;
}
}
}
//the value 10 is "embedded" to the returned object
var myobj = obj(10);
//every call to inc increments that "embedded" value
console.log(myobj.inc()); //11
console.log(myobj.inc()); //12
console.log(myobj.inc()); //13
//but you can never access the variable of `x` directly without a "getter"
console.log(myobj.getX());
Closures are one of the great features of JavaScript. One of it's great uses is to emulate private variables.
The first example you are combining functions.
Of course you can write in different ways but the idea of greaterThanTen in the first example is be something different. For example you can pass this to a filter
var a = [ 1 , 10, 100 , 9, 43 ];
function greaterThan(x) {
return function(y) {
return y > x;
};
}
var greaterThanTen = greaterThan(10);
a.filter(greaterThanTen);
returns [100, 43]
It is functional programming. There is many advantages.
Unless I missed something, the first code returns a function.
The second one returns the result.
That's not a particularly good use case. A better use case for anonymous functions is callbacks, as in: you wish to execute function #2 once function #1 is completed.
function a(param1, param2, callback) {
//work on param1 and param2 here
callback.call(); //triggers the callback function
}
Related
Thanks to this question I understand how a function may take two sets of parentheses and how a function may return another function which fires immediately after being returned.
What I do not understand is why this is good to know? How could this be applied to solve a problem?
The example of:
function add(x){
return function(y){
return x + y;
};
}
add(3)(4) === 7; // true
Works fine - sure. But why not just write it like this instead?
function add(a, b) {
return a + b;
}
add(3, 4) === 7; // true
Lets take the same code which you have mentioned.
function add(x) {
return function(y) {
return x + y;
};
}
var adder3 = add(3); //Forming adder3
var op1 = adder3(4) // 7
var op1 = adder3(5) // 9
// Now adder 10:
var adder10 = add(10); //Forming adder3
var op1 = adder10(4) // 14
var op1 = adder10(5) // 15;
Hope you understand!!
Revert me if you need more info on closure.
Your example called as closures
Closures’ Rules and Side Effects
Closures have access to the outer function’s variable even after the outer function returns:
One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:
function celebrityName(firstName) {
var nameIntro = "This celebrity is ";
// this inner function has access to the outer function's variables, including the parameter
function lastName(theLastName) {
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}
var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.
// The closure (lastName) is called here after the outer function has returned above
// Yet, the closure still has access to the outer function's variables and parameter
mjName("Jackson"); // This celebrity is Michael Jackson
Closures store references to the outer function’s variables; they do not store the actual value.
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:
function celebrityID() {
var celebrityID = 999;
// We are returning an object with some inner functions
// All the inner functions have access to the outer function's variables
return {
getID: function() {
// This inner function will return the UPDATED celebrityID variable
// It will return the current value of celebrityID, even after the changeTheID function changes it
return celebrityID;
},
setID: function(theNewID) {
// This inner function will change the outer function's variable anytime
celebrityID = theNewID;
}
}
}
var mjID = celebrityID(); // At this juncture, the celebrityID outer function has returned.
mjID.getID(); // 999
mjID.setID(567); // Changes the outer function's variable
mjID.getID(); // 567: It returns the updated celebrityId variable
Reference site : http://javascriptissexy.com/understand-javascript-closures-with-ease/
Functions which return functions are useful when you want similar functions which depend on some parameters.
A real life example: [].sort can be called with a custom comparator function, but it can make sense to define a comparator function to allow more customizations:
function comparator(options) { // Function which returns a function
return function(a, b, tmp) {
if(options.reverse) tmp = a, a = b, b = tmp;
if(options.map) a = options.map(a), b = options.map(b);
if(options.func) return options.func(a, b);
return a < b ? -1 : (b < a ? 1 : 0);
}
}
Then you can use
[1,11,10,2].sort(comparator({map: String})); // [1, 10, 11, 2]
[1,11,10,2].sort(comparator({reverse: true})); // [11, 10, 2, 1]
[1,11,10,2].sort(comparator({func: Function.prototype})); // [1, 11, 10, 2]
if we require a function in certain state with certain value then we can use it inside another function and return that, so that the return function with certain state can be directly used in different scenario.
you can check out various example on closure.
http://javascriptissexy.com/understand-javascript-closures-with-ease/
If you know the first param is always going to be the same, then it will convenient to have it closure, instead of passing it again and again. For simple programs, it may not make sense. But, for programs which handles repetitive params more often, this technique definitely comes handy.
Other than closures you can also use it for pre-processing as a one time job, consider if you had to do something intensive, e.g. generate a million things;
function generateSessionSecrets(lock) {
var secrets = [], i = 1000000;
while (i-- > 0) {
secrets[i] = Math.random();
}
return function(key, i) {
if (key === lock) return secrets[i];
}
}
var chest = generateSessionSecrets('fizz');
chest('fizz', 0); // e.g. 0.2096199430525303
chest('fizz', 1); // e.g. 0.30329699837602675
// ...
chest('fizz', 0); // still 0.2096199430525303
(This is an example of concept, not an example of real security)
there isn't a point to using it immediately. you would use it to create a function to attach it to an event or use as a callback for an asynchronous function. an example might be such:
function factory(param){
return function(result) {
if (result==param) dosomething();
}
}
$('#domobject').click({
param = $('#domvalue').value;
asynch_function(factory(param));
});
Here I've attached a click event to presumably a button. When it is clicked it will retrieve the value of an input and create a function based on it and call an asynchronous function with the newly created function as it's callback. The asynchronous function might be an ajax request. When the asynchronous function completes the function that factory created, the callback, will be called. It will check the return value the asynchronous function passed to the callback against the param specified when the event was attached.
If we move the dom lookup to inside the callback function, then we wouldn't need factory or param, but then it would use the value that is in the input at the time when the asynch function has returned, rather than when the button was clicked which is later and the value might have changed.
Sometimes, you won't be able to obtain a value you need in the context of the callback for other reasons. Or it might just be that you want to abstract out a class of functions so you don't have to retype a slightly different version of it in all the places you use it.
I am currently reading Eloquent Javascript Chapter 5. They give the following example which is confusing the hell out of me.
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true
Can anyone break this down to me as simply as possible. I have huge trouble with callbacks. Especially when it comes to situations like these.
Higher-Order functions basically mean two things:
Functions can take other functions as an argument/input
Functions can return functions
This is what is meant by higher-order functions.
// this function takes a function as an argument
function myFunc(anotherFunc) {
// executes and returns its result as the output which happens to be a function (myFunc)
return anotherFunc();
}
// let's call myFunc with an anonymous function
myFunc(function() {
// this returns a function as you see
return myFunc;
});
As for your example, it demonstrates higher-order functions by returning a function. It also demonstrates the notion of closure.
Closure is closing over a scoped variable, in this case the input argument n.
function greaterThan(n) {
// n is closed over (embedded into and accessible within) the function returned below
return function(m) { return m > n; };
}
// greatherThan10 reference points to the function returned by the greaterThan function
// with n set to 10
// Notice how greaterThan10 can reference the n variable and no-one else can
// this is a closure
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true
There's no "callback" involved here. What you've got with the "greaterThan" function is a function that returns another function.
So, you call the function:
var greaterThan10 = greaterThan(10);
Now the variable "greaterThan10" references the function returned by the "greaterThan" function invoked with 10 as the argument.
Then, you log the result of calling that function:
console.log(greaterThan10(11));
The function returned from "greaterThan" is invoked. It compares its parameter to the value of the parameter "n" passed when it was created. Because 11 is in fact greater than 10, the function will return true and that's what'll be logged.
I have done a fair amount of research but have not been able to find any answers, to what seems like a simple question:
I want to associate a property with a function (to use as a static variable in this function), like so:
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
If I change the name of the function later, I don't want to have to change references to it inside function definition.
So, is there a way to refer to the currently executing function? (other than arguments.callee which is now deprecated). A keyword like thisFunction?
If not, what is the reason for not having something like this?
I do not know of an identifier or keyword like thisFunction (besides arguments.callee) that JavaScript exposes, but one way to achieve the same effect is to name the function foo in a closure, and return foo from that closure. That way you can always use the name foo within foo to refer to itself, regardless of what variable it's assigned to by your program:
var fn = (function() {
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
return foo;
})();
function foo() {
if (typeof foo.counter=="undefined") {
foo.counter = 1;
}
else {
foo.counter++
}
return foo;
}
var x = new foo();
alert(x.counter); //1
var y = new foo();
alert(x.counter); //2
If you don't need to refer to the counter outside of the function, this will work. Instead of setting a variable of the function itself, you define a variable outside of the function and let the function modify that instead. Every time you call makeFoo, it makes a new variable x and returns a function using x. Every time you call the returned function, it still refers to the same x created by makeFoo. Additionally, this entirely encapsulates the variable, ensuring that almost nothing outside of the returned function can change it (it definitely won't be changed by most things outside of the returned function, but there is enough funky javascript reflection that I can't guarantee that nothing will change it). Certainly, moving the function between variables won't affect the counter (ie x=makeFoo();y=x;x=null;).
function makeFoo() {
var x=0;
return function () {
x++;
return x;
}
}
//different counters
x=makeFoo();
y=makeFoo();
x();//returns 1
y();//returns 1
x();//returns 2
y();//returns 2
//same counter
x=makeFoo();
y=x;
x();//returns 1
y();//returns 2
x();//returns 3
y();//returns 4
Following are two ways to define BW.Timer. Can someone tell me what the difference is? I am not certain the first is even valid, but if it is valid, what is different about using the myfunc=(function(){}()) syntax?
BW.Timer = (function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
} ());
And...
BW.Timer = function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
};
The first is the return-value of the immediately-invoked function. The second is a function. It essentially comes down to what the difference is between these:
var f = (function() { return 0; })();
var f = function() { return 0; };
Since the first function is called immediately, the value of 0 is given to the variable f. The first f is not a function. However, the second f we must call in order to get the value:
f(); // 0
It follows that in your example, the first BW.Timer is the object literal itself and the second is a function returning an object literal. You must call the function in order to get to the object:
BW.Timer().Add(x);
Why use the first then?
You might ask yourself why one would use a syntax like a = (function() { return {}; })() instead of a = {}, but there's a good reason. An IIFE (Immeditately-Invoked Function Expression), unlike a regular function allows the emulation of static variables (variables that maintain their value through a single instance). For example:
var module = (function() {
var x = 0;
return { get: function() { return x },
set: function(n) { x = n }
};
})();
The above a text-book example of the Module Pattern. Since the function is called right away, the variable x is instantiated and the return value (the object) is given to module. There's no way we can get to x other than by using the get and set methods provided for us. Therefore, x is static, meaning its variable won't be overridden each time you use module.
module.set(5);
module.get(); // 5
On the other hand, let's see an example where module is declared as a function instead:
// assume module was made as a function
module().set(5);
module().get(); // 0
When we call module() the x variable is overridden each time. So we're effectively using different instances of module and x each time we call module.
The difference is rather large.
In the first case, BW.Timer is executed when it is first encountered, and that is the static version assigned to BW.Timer. In that instance, BW.Timer.Add(1) may be used. Each call to BW.Timer will be the same object.
In the second case, BW.Timer is not executed when first encountered, and instead is a function referece which must be invoked BW.Timer(). For Add to be used, this must be the case BW.Timer().Add(1). Also, you can issue var timer = new BM.Timer();. Each instance of BW.Timer() will be unique here.
In the first example BW.Timer references an object that the self-executing function returns, while in the second example it references a function object, in other words it's a function that can be executed BW.Timer().
I want to pass a function reference "go" into another function "redefineFunction", and redefine "go" inside of "redefineFunction". According to Johnathan Snook, functions are passed by reference, so I don't understand why go() does not get redefined when I pass it into redefineFunction(). Is there something that I am missing?
// redefineFunction() will take a function reference and
// reassign it to a new function
function redefineFunction(fn) {
fn = function(x) { return x * 3; };
}
// initial version of go()
function go(x) {
return x;
}
go(5); // returns 5
// redefine go()
go = function(x) {
return x * 2;
}
go(5); // returns 10
// redefine go() using redefineFunction()
redefineFunction(go);
go(5); // still returns 10, I want it to return 15
Or see my fiddle http://jsfiddle.net/q9Kft/
Pedants will tell you that JavaScript is pure pass-by-value, but I think that only clouds the issue since the value passed (when passing objects) is a reference to that object. Thus, when you modify an object's properties, you're modifying the original object, but if you replace the variable altogether, you're essentially giving up your reference to the original object.
If you're trying to redefine a function in the global scope: (which is a bad thing; you generally shouldn't have global functions)
function redefineFunction(fn) {
window[fn] = function() { ... };
}
redefineFunction('go');
Otherwise, you'll have to return the new function and assign on the calling side.
function makeNewFunction() {
return function() { ... };
}
go = makeNewFunction();
Nothing is "passed by reference" in JS. There are times that references are passed, but they're passed by value. The difference is subtle, but important -- for one thing, it means that while you can manipulate a referenced object pretty much at will, you can't reliably replace the object (read: alter the reference itself) in any way the caller will see (because the reference was passed by value, and is thus merely a copy of the original reference; attempting to reassign it breaks in the same way it would if the arg were a number or string).
Some cowboys will assume you're redefining a global function and mess with it by name to get around the limitations of pass-by-value, but that will cause issues the second you decide not to have globals all over the place.
The real solution: return the new function, and let the caller decide what to do with it. (I'd argue that redefining functions right out from under the code that uses them is a pretty bad design decision anyway, but eh. I guess there could be a reason for it...)
Snook is wrong. And I don't think it's pedantic at all (#josh3736 :) to point out that EVERYTHING in JavaScript is pass by value. The article by Snook gets this COMPLETELY wrong. Passing a primitive and passing an object work the exact same way. These are equivalent:
var x = 2;
var y = x;
y = 3; //x is STILL 2.
function stuff(y){
y = 3; //guess what. x is STILL 2
}
stuff(x);
///////////////////
var x = {stuff: 2};
var y = x;
y = {stuff: 3}; //x.stuff is STILL 2
function stuff(y){
y = {stuff: 3}; //guess what. x.stuff is STILL 2
}
stuff(x);
This is important. Java, C#, and MOST languages work this way. That's why C# has a "ref" keyword for when you really do want to pass something by reference.
You can't modify the variable from inside the function, so the quick fix is to return the value and assign it outside the function, like this
// log() just writes a message to the text area
function log(message) {
$('#output').val($('#output').val() + message + "\n");
}
// redefineFunction() will take a function reference and
// reassign it to a new function
function redefineFunction() {
newvalue = function(x) { return x * 3; };
return newvalue;
}
// initial version of go()
function go(x) {
return x;
}
log(go(5)); // returns 5
// redefine go()
go = function(x) {
return x * 2;
}
log(go(5)); // returns 10
// redefine go() using redefineFunction()
go = redefineFunction();
log(go(5)); // returns 10, I want it to return 15
I believe functions are 'passed in by value'. If you put log(f(5)); inside your redefineFunction function it will output 15, but 10 when you call log(go(5)) afterwards.
If you change redefineFunction to return the function and then assign it to go (go = redefineFunction()) it will work as you expect.
This is equivalent to asking if you can redefine any variable by passing it as an argument to some function. No. You can reassign it by, uhh, reassigning it. In this case, if you make redefineFunction return a function, you can simply assign it to go:
function redefineFunction() {
var fn = function(x) { return x * e; };
return fn;
}
function go(x) {
return x;
}
go = redefineFunction();
go(5); // return 15
This is working in firefox:
function redefineFunction(fn) {
window[fn] = function(x) {
return x * 3;
}
};
function go(x) {
return x;
};
alert(go(5));
go=function(x) {
return x * 2;
}
alert(go(5));
redefineFunction('go');
alert(go(5));
The secret is that a global function called go also is called window.go and window["go"].
This can also be used at styles: element.style["overflow"] = "hidden", and in attributes:
element["value"] = "hello there".
This is a very useful knowlege.
Why dont use a object? something like this:
var o = {
go: function( x ) {
return x;
},
redefineFunction: function ( fn ) {
if (typeof fn === 'function') {
this.go = fn;
}
}
}
console.log(o.go(5)); // return 5
var fn = function (x) {
return x * 2;
};
o.redefineFunction(fn);
console.log(o.go(5)); //return 10
Hope it helps!