1.
function abc(){
alert("named function");
}
v/s
2.
function(){
alert("Un-Named function");
}
Kindly explain from beginners point.
They work exactly the same. It's only in how you are able to run them that they are different.
So example #1 you could call again at any point with abc();. For example 2, you would either have to pass it as a parameter to another function, or set a variable to store it, like this:
var someFunction = function() {
alert("Un-Named function");
}
Here's how to pass it into another function and run it.
// define it
function iRunOtherFunctions(otherFunction) {
otherFunction.call(this);
}
// run it
iRunOtherFunctions(function() {
alert("I'm inside another function");
});
As David mentions below, you can instantly call it too:
(function() {
alert("Called immediately");
})(); // note the () after the function.
Both can be used to achieve the same but the main difference is the anonymous functions don't need a name. Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.
Please refer this link
Related
Is it possible to pass a javascript function with parameters as a parameter?
Example:
$(edit_link).click( changeViewMode( myvar ) );
Use a "closure":
$(edit_link).click(function(){ return changeViewMode(myvar); });
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.
Use Function.prototype.bind(). Quoting MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
It is supported by all major browsers, including IE9+.
Your code should look like this:
$(edit_link).click(changeViewMode.bind(null, myvar));
Side note: I assume you are in global context, i.e. this variable is window; otherwise use this instead of null.
No, but you can pass one without parameters, and do this:
$(edit_link).click(
function() { changeViewMode(myvar); }
);
So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure
Or if you are using es6 you should be able to use an arrow function
$(edit_link).click(() => changeViewMode(myvar));
Yes, like this:
$(edit_link).click(function() { changeViewMode(myvar) });
You can do this
var message = 'Hello World';
var callback = function(){
alert(this)
}.bind(message);
and then
function activate(callback){
callback && callback();
}
activate(callback);
Or if your callback contains more flexible logic you can pass object.
Demo
This is an example following Ferdinand Beyer's approach:
function function1()
{
function2(function () { function3("parameter value"); });
}
function function2(functionToBindOnClick)
{
$(".myButton").click(functionToBindOnClick);
}
function function3(message) { alert(message); }
In this example the "parameter value" is passed from function1 to function3 through function2 using a function wrap.
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 want to create a closure dynamically. See code below for explanation.
function myFunction(){
parentScopedVar(); //Would like to be able to call without using 'this'.
}
function myDynamicFunc(dynamicClosure){
//What do I need to do here to dynamically create
//a var called 'parentScopedVar' that can be referenced from myFunction?
myFunction.call(self);
}
myDynamicFunc(
{
parentScopedVar : function() { alert('Hello World'); }
});
Javascript uses lexical scope (based on where the code is declared), not dynamic scope.
If you are determined to try to do something that the language doesn't really encourage, you can force a string of code to be evaluated in your current execution context using eval(string of code here). In fact, you can do all sorts of odd things with eval(), but I'd much rather write code in a way that leverages the strengths of Javascript than to use a coding style that goes against the main design theme of the language (that's my opinion).
It's not entirely clear to me what problem you're trying to solve, but you can just pass a function as an argument and then call it via the argument from the called function.
// declare your function that takes a function reference an argument
function myFunction(callback) {
// call the function that was passed
callback();
}
function myDynamicFunc(){
// declare a local function
function myAlert() {
alert('Hello World');
}
// call your other function and pass it any function reference
myFunction(myAlert);
}
This will not pass an entire execution context. To do that, you'd have to package up the context in an object and pass a reference to the object, then dereference the properties from the object. That is typically how you pass an environment in JS.
You can use locally declared functions to provide access to parent scope from a callback (again lexical scope):
// declare your function that takes a function reference an argument
function doSomething(callback) {
// call the function that was passed
callback();
}
function myFunc() {
var myLocal1 = "Hello";
var myLocal2 = "World";
function callback() {
// when this is called, it has access to the variables of the parent scope
alert(myLocal1 + " " + myLocal2);
}
doSomething(myFunc);
}
You can even use it as a lasting closure:
// declare your function that takes a function reference an argument
function doSomething(callback) {
// call the function that was passed
callback();
}
function myFunc() {
var myLocal1 = "Hello";
var myLocal2 = "World";
function callback() {
// when this is called, it has access to the variables of the parent scope
// which are still alive in this closure even though myFunc has finished
// executing 10 minutes ago
alert(myLocal1 + " " + myLocal2);
}
// call the callback function 10 minutes from now,
// long after myFunc has finished executing
setTimeout(callback, 10 * 60 * 1000);
}
Here are some reference articles on lexical and dynamic scope in Javascript:
Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?
Are variables statically or dynamically "scoped" in javascript?
What is lexical scope?
*Is there a way to call a function defined inside another function in javaSCRIPT? For example:
window.onload() = function() {
function my_function(){
print("Blah");
};
};
function function_two(){
my_function();
};
Is there a way to do something like the above (calling my_function in function_two even though it's defined inside the window.onload() function)? In my actual code, which also uses the raphael.js library, I'm trying to write a button in HTML, which using the onClick function, calls a function(like function_two) that runs the function defined in window.onload() (like my_function). However the console says that the my_function is undefined.
The scope of the function is the core issue here, as Zeychin and Trevor have said. I thought I'd offer another way of handling it. Basically, you can set your function to a variable that's in a higher scope (that is, accessible to both the onload and function_two functions), while defining it inside the onload function as you originally have:
var myFunction; //This is the placeholder which sets the scope
window.onload() = function() {
myFunction = function() { //Assign the function to the myFunction variable
print('blah');
}
}
function function_two() {
myFunction();
}
This might be handy if you only know the information you need for myFunction once you're in the onload event.
You can not do what you are asking to do.
The function my_function()'s scope is only within the anonymous function, function(). It falls out of scope when the method is not executing, so this is not possible.
Trevor's answer is the way to do this.
window.onload = function() {
my_function()
};
function my_function(){
alert("Blah");
};
function function_two(){
my_function();
};
Is it possible to pass a javascript function with parameters as a parameter?
Example:
$(edit_link).click( changeViewMode( myvar ) );
Use a "closure":
$(edit_link).click(function(){ return changeViewMode(myvar); });
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.
Use Function.prototype.bind(). Quoting MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
It is supported by all major browsers, including IE9+.
Your code should look like this:
$(edit_link).click(changeViewMode.bind(null, myvar));
Side note: I assume you are in global context, i.e. this variable is window; otherwise use this instead of null.
No, but you can pass one without parameters, and do this:
$(edit_link).click(
function() { changeViewMode(myvar); }
);
So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure
Or if you are using es6 you should be able to use an arrow function
$(edit_link).click(() => changeViewMode(myvar));
Yes, like this:
$(edit_link).click(function() { changeViewMode(myvar) });
You can do this
var message = 'Hello World';
var callback = function(){
alert(this)
}.bind(message);
and then
function activate(callback){
callback && callback();
}
activate(callback);
Or if your callback contains more flexible logic you can pass object.
Demo
This is an example following Ferdinand Beyer's approach:
function function1()
{
function2(function () { function3("parameter value"); });
}
function function2(functionToBindOnClick)
{
$(".myButton").click(functionToBindOnClick);
}
function function3(message) { alert(message); }
In this example the "parameter value" is passed from function1 to function3 through function2 using a function wrap.