Node.js vs Javascript Closure - javascript

I'm working my way through the Eloquent JavaScript Book and in it there is the following code:
function createFunction(){
var local = 100;
return function(){return local;};
}
When I run this via the node console (run node from command prompt) by calling createFunction(), I get [Function] as a returned value. However, according to the book I should get 100.
So my two questions: Why is this? and Second, is running these little examples in the node console a bad idea for testing JS code?

You need to call the response of createFunction().
createFunction()();
The first invocation (()) calls createFunction() and returns the inner function, which the second invocation executes and returns the local variable which was closed over.
Running small examples in a node console (or any other) is fine, so long as you know the environment, e.g. a browser's console is generally eval()'d, which can create side effects, such as how delete can apparently delete variables, not just object properties.

You get 100 by invoking the return value of createFunction, which is itself a function.
createFunction()();
...or perhaps more clearly...
var new_func = createFunction();
new_func();
function createFunction(){
var local = 100;
// v---v-----------------------v return a function from createFunction
return function(){return local;};
}
// v------- the returned function is assigned to the new_func variable
var new_func = createFunction();
// v------- the returned function is invoked
new_func();

For those that have a similar problem, I completely missed the double () so the call looks like createFunction()().

Related

How to console.log the content of a closure

I would like to see the content of a closure in JavaScript.
In the following code, I would like to see the closure of the function closure_f returned by the anonymous function. The local scope of the anonymous function must be stored somewhere, I would like to see where it is stored. How can this be done in Node or in the browser?
var closure_F = (function(){
var info = "info-string";
var f1 = function(){
console.log(info);
};
return f1;
}());
closure_F(); // logs 'info-string' as expected.
console.log(closure_F); // This did not provide any valuable information.
WAY 1: Internal property [[Scope]]
You can modify your code by adding console.dir and then run it in the Chrome Dev Console:
var closure_F = (function(){
var info = "info-string";
var f1 = function(){
console.log(info);
};
return f1;
}());
closure_F();
console.dir(closure_F);
// console.dir prints all the properties of a specified JavaScript object
If you open the console you will see that it prints all the properties of the object (function), including the internal property [[Scopes]].
This internal property [[Scopes]] will contain any surrounding scopes of the closure_f, and its closure. See example:
Note: [[Scope]] is an internal implementation of JS and cannot be programatically accessed within the program.
WAY 2: Setting a breakpoint - debugger
Another way to see the Closure of a function is to add a debugger statement and create a break point in the function who's closure you want to inspect.
As an example you can run this in the console:
function createClosure (){
var secret = "shhhhh";
return function inner(){
debugger;
console.log(secret);
};
};
var innerFunction = createClosure();
innerFunction();
www.ecma-international.org >> [[Scope]] >> Table 9
The local scope of the anonymous function must be stored somewhere
That's an implementation detail of the JavaScript runtime. It isn't stored anywhere that is exposed to the JavaScript program.
How can this be done in Node or in the browser?
Dedicated debugging tools can inspect the data there. Set a breakpoint on the console.log call.
Note that optimisations mean that only variables used within the returned function will be visible.

Differences when using functions for casper.evaluate

I'm using PhantomJS v2.0 and CasperJS 1.1.0-beta3. I want to query a specific part inside the page DOM.
Here the code that did not work:
function myfunc()
{
return document.querySelector('span[style="color:#50aa50;"]').innerText;
}
var del=this.evaluate(myfunc());
this.echo("value: " + del);
And here the code that did work:
var del=this.evaluate(function()
{
return document.querySelector('span[style="color:#50aa50;"]').innerText;
});
this.echo("value: " + del);
It seems to be the same, but it works different, I don't understand.
And here a code that did also work:
function myfunc()
{
return document.querySelector('span[style="color:#50aa50;"]').innerText;
}
var del=this.evaluate(myfunc);
this.echo("value: " + del);
The difference here, I call the myfunc without the '()'.
Can anyone explain the reason?
The problem is this:
var text = this.evaluate(myfunc());
Functions in JavaScript are first class citizen. You can pass them into other functions. But that's not what you are doing here. You call the function and pass the result into evaluate, but the result is not a function.
Also casper.evaluate() is the page context, and only the page context has access to the document. When you call the function (with ()) essentially before executing casper.evaluate(), you erroneously try to access the document, when it is not possible.
The difference to casper.evaluate(function(){...}); is that the anonymous function is defined and passed into the evaluate() function.
There are cases where a function should be called instead of passed. For example when currying is done, but this is not applicable to casper.evaluate(), because it is sandboxed and the function that is finally run in casper.evaluate() cannot use variables from outside. It must be self contained. So the following code will also not work:
function myFunc2(a){
return function(){
// a is from outer scope so it will be inaccessible in `evaluate`
return a;
};
}
casper.echo(casper.evaluate(myFunc2("asd"))); // null
You should use
var text = this.evaluate(myfunc);
to pass a previously defined function to run in the page context.
It's also not a good idea to use reserved keywords like del as variable names.

QlikView runs BodyOnLoadFunctionNames callbacks too early - why?

I have a problem with QlikView in the browser: I have a listbox and try to access it using an initialize script.
The script is registered by using the InitWorkbench function, using its BodyOnLoadFunctionNames parameter. So far, this works, and the initializer is run at startup.
Inside the initializer I try to do the following:
var doc = Qv.GetCurrentDocument();
var listbox = doc.GetObject('LB01');
Afterwards, when I have a look at listbox.Type, unfortunately it is undefined. If I delay execution of this query, it correctly says LB, hence apparently the query works - but only when it is executed delayed.
So, obviuosly there's a timing problem, and it seems as if the initializer runs too early (or I am doing something wrong).
Can anybody point out what the solution is (or give me a hint on what I am doing wrong)?
Okay, I've found the solution: The internal update function did not run yet, and all the values are only available once this function ran, so you need to provide a callback to the call to GetObject (that gets called after the update function):
var doc = Qv.GetCurrentDocument();
var listbox = doc.GetObject('LB01', function () {
console.log(listbox.Type); // => 'LB'
});

javascript OOP Confusion [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript OOP return value from function
I have a class defined like this
function SocialMiner(tabUrl)
{
var verbose=true;
var profileArray=new Array();
this.tabUrl=tabUrl;
this.getTabUrl=function(callback)
{
chrome.tabs.getSelected(null, function(tab)
{
callback(tab.url);
});
}
this.setTabUrlValue=function(pageUrl)
{
this.tabUrl=pageUrl;
console.log("22"+this.tabUrl); //this statement shows url correctly
}
}
When I call this method like these
miner.getTabUrl(miner.setTabUrlValue);
miner.logToConsole("1"+miner.tabUrl); //This statement returns undefined
The console.log inside callback correctly outputs url , however, the tabUrl property of miner ojbect is undefined , as seen in second console.log. Why is it so ?
The solution is to save a reference to this within the constructor (available later on via closure):
var that = this; //in the top of the SocialMiner constructor function
and in setTabUrlValue use:
that.tabUrl=pageUrl;
I suspect running a method as a function (callback) loses scope, i.e. doesn't know of any this anymore. In other words, it runs within the scope of the constructor, not as a method of the instance using it. A variable referencing this in the constructor scope is available to the function, and that points to the right this on instance creation.
You could also force callback to run in the current instance scope like this:
callback.call(this,tab.url);
In that case you can leave this.tabUrl=pageUrl; as it is.
This is an simplification of your code. The methods return this to be able to directly reference a property of the instance (see console.log last line):
function Some(){
var that = this; // note: not used in this example
this.getA = function(callback){
someval = 'foobar';
callback.call(this,someval);
return this;
};
this.getB = function(val){
this.val = val;
return this;
};
}
var some = new Some;
console.log( some.getA(some.getB).val ); //=> foobar
Taking a look # your code again, I think you're loosing scope twice, because callback is called from within another callback. That's why I think your code on that spot should be:
chrome.tabs.getSelected(
null,
function(tab) {
callback.call(that,tab.url); //< use that here
}
);
Furthermore, in you code # github, I don't see any instantiation of the miner instance.
this is a tricky beast in JavaScript and as others have pointed out is the key to the issue. The problem with using this everywhere is that it's value can change depending on who/where the function is called from (for example, see the call and apply methods in JavaScript). I'm guessing that if you wrote the value of this to the console in the the callback from the chrome.tabs.getSelected function you'd find it isn't your miner any more.
The solution is to capture a reference to the this that you're actually interested in when you know for sure it's the right one & then use that reference from then on. Might make more sense to see it commented in-line in your example:
function SocialMiner(tabUrl)
{
//At this point we know "this" is our miner object, so let's store a
//reference to it in some other (not so transient) variable...
var that = this;
var verbose=true;
var profileArray=new Array();
this.tabUrl=tabUrl;
this.getTabUrl=function(callback)
{
chrome.tabs.getSelected(null, function(tab)
{
//at this point "this" is whatever the "chrome.tabs.getSelected"
//method has decided it is (probably a reference to the tab or something)
callback(tab.url);
});
}
this.setTabUrlValue=function(pageUrl)
{
//because this can be called from anywhere, including the chrome callback
//above, who knows what "this" refers to here (but "that" is definitely
//still your miner)
that.tabUrl=pageUrl;
console.log("22"+that.tabUrl);
}
}
You can see how much this shifts around in libraries that use callbacks heavily like jQuery, where often this is set to convenient values, but certainly not the same this that was logically in scope when you made the initial call.
EDIT: Looking at the full source (& example) you posted, this is just a timing issue where obviously the chrome.tabs.getSelected is returning asynchronously after your "second" call to log goes through...
console.log("5");
miner.getTabUrl(miner.setTabUrlValue); //setTabUrlValue is logging with '22'
console.log("6");
miner.logToConsole("1"+miner.tabUrl);
console.log("7");
// Output:
5
6
1 undefined //the chrome.tabs.getSelected hasn't returned yet...
7
22 http://url //now it has (so if you tried to use miner.tabUrl now you'd be all good...
The solution is to put all the stuff after the get/set into the callback, since you don't want anything happening until after that tabUrl is finished being set... so something like this:
console.log("5");
miner.getTabUrl(function(pageUrl) {
miner.setTabUrlValue(pageUrl);
console.log("6");
miner.logToConsole("1"+miner.tabUrl);
console.log("7");
});
Hopefully that will see you getting your results in the order you expect them.
I think this happens because closure vars do not survive a function call.

Javascript anonymous function not updating global variable

I've got a $.getJSON call in some code that appear to be not updating a global variable, and I'm at a loss to understand why. The JSON data is being loaded OK, but for some reason the global EventOptions array is not being updated in the for {} loop. The capitalised comments refer to the variable. Any ideas? Thanks
function LoadMeasurementTypes() {
// Clear out EventOptions
EventOptions = ["..."];
// Push a couple on to EventOptions - THESE ADD OK
EventOptions.push("Temperature");
EventOptions.push("Pulse rate");
// Call json to get measurementTypes off the table
$.getJSON('./get-measurement-types.php', function (measurementTypeData) {
// Process each json element ([0].BP, [1].ph (Urine) etc.
for (var i = 0; i < measurementTypeData.length; ++i) {
// e is a storage variable to contain the current element
var e = measurementTypeData[i];
// Add the new measurement type
alert(e.measure_type); // OK works - we can see the measure_type
EventOptions.push(e.measure_type); // THESE ARE NOT BEING ADDED
}
} // end anonymous function
) // end get json call
EventOptions.push("Last one"); // THIS ONE IS BEING ADDED
}
Your EventOptions[] is not globally visible. My guess would of been that it should still be visible locally to your $.getJSON call; but because it is now scoped to jquery, its clearly obscured (did you alert(EventOptions); inside your anon function to test?.
To properly scope, just declare it outside of LoadMeasureTypes().
var EventOptions = ["..."];
function LoadMeasureTypes(){...
-update
if this does not work - you could always pull the anonymous function outside of the $.getJSON() and assign it a variable name:
var retreiveTypes = function(){...};
$.getJSON("..path/php", retreiveTypes);
window.EventOptions = ["..."]
Good 'ol "hack" to put stuff in the global context
Got the answer: well kind of. It won't work on iTouch Safari, but is fine on Firefox (Mac). Bosworth I'm figuring it's a browser issue you noted above.
Interestingly, it may be something to do with threads. It appear the out loop runs before the inner anonymous loop has finished (the alerts are not in sequence!). I didn't think javascript used threads this way, but I may be wrong.
I now suspect the whole issue is a timing one - with a new thread as an anonymous function not completing in time.
Thanks guys.

Categories