I need to call the function from browser console for testing purpose ?
test is working as expected , but test2 is not working
function test() {
alert(0);
}
(function(e, t) {
var test2 = (function() {
alert(2)
})
})
Calling for browser console
test() // its working
test2() // Uncaught ReferenceError: test2 is not defined
There are two basic problems here:
test2 never exists
test2 is defined inside a function which is never called, so it is never defined.
The code would have to actually call the anonymous function it is inside.
However, assuming that is a side effect of you truncating the code for this question and in your real case that anonymous function does get called:
test2 isn't a global
So in order to access it, you need to be in the right scope.
The only way to do that for the console would be to:
open up the sources tab of the browser's developer tools
add a breakpoint inside the anonymous function
run the code until your reach the breakpoint
then use the console to access test2 which is now in scope.
Note that given the structure of that code you might have to put the breakpoint before test2 has a value assigned to it and then step through the code until after it is defined.
Since your test2 var is a function on it's own, no need to wrap them in ().
Copy/paste this into browser console to check;
var test2 = (function() {
alert(2)
});
test2();
Advanced JavaScript: Why is this function wrapped in parentheses?
Should you really want those parentheses, you can call the existing function like so;
(function(e, t) {
var test2 = (function() {
alert(2)
});
test2(); // <-- Run function
})()
//^^ Extra parentheses to instantly run wrapper function
Related
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.
I am currently try to run some JavaScript within my robot framework code that creates a new function, and then uses the newly created function to return a value upon calling it. However, when I log the result to the console, I do. It get my desired output. Please help!
The code:
${test}= Execute Javascript return function test(){return 1}; test();
Log To Console ${test}
The console output:
{}
Move the return statement after the function definition, otherwise the return happens before test() is called.
*** Settings ***
Library Selenium2Library
*** Test Cases ***
Example
[Setup] open browser about:blank chrome
[Teardown] close all browsers
${test}= execute javascript function test() {return 1}; return test();
should be equal as strings ${test} 1
The below code snippets are not the actual code, they are only there to explain my issue. So please don't concentrate on the actual functionality. I'm working with Adobe DTM. I have no idea how to get an anonymous function that returns a value (as a Data Element to source a global function? If I have a normal anonymous function within my data Element, everything works fine. If the anonymous function returns, then it doesn't work? Is there any way to get this to work? Example:
//global function
function _myGlobalFunct(str){
return (str);
}
the following code of an anonymous function within the Data Element calls global function and it works as expected:
// working anonymous function
(function () {
window._myGlobalFunct("value1");
})()
but the following return anonymous function, within the Data Element, doesn't call my function but doesn't throw any errors? :
// Not Working Properly but doesn't throw any errors?
return (function() {
var rvalue = document.title || "No Title";
window._myGlobalFunct(rvalue);
return rvalue;
})();
I do know the function is executing but not getting any errors in Chrome?
DTM's data elements execute the code provided within a function (that may not be clear to the other users here), so there will be a return outside of a function in the code you input/show here. You're not returning the value from your function (or if you're trying to update rvalue within the function and rvalue isn't in the right scope (window vs. local)). In any case, is there a reason you're using the anonymous function anyways? Below should work:
var rvalue = document.title || "No Title";
return window._myGlobalFunct(rvalue);
If you still want the anonymous function, make sure to grab the return value from your function:
return (function() {
var rvalue = document.title || "No Title";
return window._myGlobalFunct(rvalue);
})();
I don't think you can return a self-invoking function and then return again in the function.
Since I can't comment yet I will explain it here in more detail, why it is indeed a duplicate. The first answer by Niet the Dark Absol in the link I mentioned above(for reference: Syntax error: Illegal return statement in JavaScript), clearly says the following:
return only makes sense inside a function. There is no function in
your code.
To apply this to your case:
return (function() {
Is your first line, if you would encapsulate everything in another function and call that one everything will be working fine, e.g.:
function myFunction(){
return (function() {
var rvalue = document.title || "No Title";
window._myGlobalFunct(rvalue);
return rvalue;
})();
}
And then you can call myFunction() to get your return value. I hope this helps you out.
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.
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()().