i am total newbie to JS.
now i have read in a book this code.
var sayMessage = new Function("message", "console.log(message);");
My Question is where are the {} in this function.
i mean how can we write message", "console.log(message); where there needs to be a argument?
thanks.
The JavaScript Function constructor can be used to define functions from strings. The constructor will evaluate the string passed as the last argument as the function body.
Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.
From the documentation.
That means this statement:
var sayMessage = new Function("message", "console.log(message);");
will be evaluated to this expression:
var sayMessage = function (message) {
console.log(message);
};
You can see how the arguments message and console.log(message) map from one to the other.
There are very few reasons why you would like to do this in the first place, and it is rarely seen in idiomatic JavaScript.
Related
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 6 years ago.
I have string logo.cr.Button and function
logo.cr.Button = function(){
//something
}
var strg = 'logo.cr.Button';
strg();
now somehow i have to make that string a function call
like strg(); but it is saying
strg is not a constructor
here
Generally when we write JavaScript functions the resulting function declaration looks like this:
function demo() {
// function stuff here
}
You’re probably more than aware that “In JavaScript Functions are first-class Objects”. It’s a phrase that is spouted everywhere, and for good reason. It’s a very powerful idea that has worked to elevate JavaScript to where it is. We’re not going into the details of first-class objects here. All we care about is the fact that, in JavaScript, functions are objects.
This means that the above function can also be declared by calling its Constructor:
var demo = new Function();
Now lets imagine we have a function with parameters and instructions:
function demo(name, age) {
console.log('my name is ' + name);
console.log('my age is ' + age);
}
and now to convert it to Constructor syntax:
var demo = new Function(
"name,age",
"console.log('my name is ' + name);" +
"console.log('my age is ' + age);"
);
This makes it pretty easy to see that these two functions are the same, they are just declared differently. The important difference is that one has easily accessible strings that we should be able to manipulate.
This applies to your function in a very similar way.
var strfunc = new Function ("", "logo.cr.Button()");
I can't seem to format this because I'm on mobile. But i will asap.
Use eval("logo.cr.Button")();
This will execute the function, of course if you have an object like:
var logo = {
cr: {
}
};
This won't work because JavaScript thinks you are using dot notation. When you write logo.cr.Button() JavaScript is looking for a function Button() within the object cr which is in the object logo.
I recommend changing the name to logoCrButton = function()...
You could use eval, but its not recommended.
Secury issues are just one reason, because an user might exploit eval to execute different code that is not supposed to be executed. Within this question it is explained fully.
var logo={cr:{}};
logo.cr.Button = function(){
console.log("something");
}
var string = "logo.cr.Button()";
eval(string);
If you can avoid eval then use a normal function call, an object or an array instead. For insteads Iterating through an array is much better and more stable compared to evaluating some parameters dynamically, as you can see here.
This second example does not use eval, but nevertheless you can call a certain function by using a string:
var obj={logo:{cr:{Button:function(){console.log("something");}}}};
var string = "logo.cr.Button";
function callFunctionByString(string,obj){
var parts = string.split('.');
parts.forEach(function(part){
obj = obj[part];
});
obj();
}
callFunctionByString(string,obj);
Hope this helps.
Hello I've come across this piece of code and I have no idea how it works.
function firstFunction(something, else){
//stuff being done
return something;
}
var myFunction = firstFunction(function(a,b){
return a*b;
},'car');
So I am fairly new to Javascript so I'll just say it is, a really confusing language. I understand I am declaring a variable that is assigning the firstFunction to itself and passing some noname function as first parameter and a String as a second one.
How do I go about passing the arguments into that noname functions?
Yes, your assessment is pretty much correct, although the code has a syntax error because you can use else as an identifier. These are referred to as anonymous functions.
Function in JavaScript can be used as parameter values or return values just as easily as any other value. This is what makes them first-class citizens of the language.
The anonymous function you pass in to firstFunction is returned and assigned to myFunction so if you want to call it, you can simply do this:
var result = myFunction(4, 5); // 20
There are different ways of defining the javascript functions. I often use the simplest way to define the function
function myfunc(){
}
and the next way to define the function in the variable like this (a little bit confusing the way of using)
var myvar = myfunc(){
/*some code*/
}
and the difficult way for me and mostly found in codes developed by advanced programmers like the following
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}
Please, can anyone clear my concept on this how can I use?
function myfunc(){}
Function declaration: the function is declared using the standard syntax
function functionName(params[]) {
//functionbody
}
Using this syntax declares the function at the begin of the scope execution, so they'll be available everywhere in their scope(and in their descendeant scopes).
var s = myfunc(); //s == 0
function myfunc() {return 0;}
var myfunc = function() {};
This uses the pattern known as function expression, it just assigns a reference of an anonymous function to a variable named myfunc. Using this syntax won't allow you to use the function until the variable is parsed. Even if variables are hoisted at the top of their scope, they're initialized when the interpreter parses them, so the above example won't work:
var s = myfunc(); //ReferenceError: myfunc is not defined
var myfunc = function() {return 0;};
But the example below will:
var myfunc = function() {return 0;};
var s = myfunc(); //s == 0
The third example is just assigning an anonymous function to an object property(also known as object method) in the way we've just done with function expression, so if I use the pattern above the code will become:
var onOpen = function() {},
onClose = function() {},
SqueezeBox = {//curly braces denotes an object literal
presets: {//again, this is a nested object literal
onOpen: onOpen,
onClose: onClose
}
};
This acts exactly the same as your example, with the only difference that here I used a variable to get a reference to the anonymous function before passing it to the object. If you need to know more about objects, I recommend you reading the MDN docs. Anyway, if you're really intrested in how JS works, I'd suggest Javascript Garden, which is a very good article about JS.
The first code snippet is a function declaration:
function myfunc() { }
You are declaring a named function called myfunc. You can verify this by myfunc.name === "myfunc"
Your second code snippet contains syntax error. I believe you meant:
var myvar = function() { };
This is an anonymous function expression assigned to a variable. You can verify this by typeof myvar === "function" and myvar.name === "".
The third snippet is a javascript object. Basically you can think of it as a Map or Dictionary<string, object>. So SqueezeBox contains 1 key presets, which in turn is a dictionary that contains 2 keys, onOpen and onClose, which both of them are anonymous functions.
In
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}}
He's creating an object SqueezeBox containing another object presets with two empty anonymous functions, he's defining the function inline with an empty body inside the {}.
A better way to see it is formatted this way:
var SqueezeBox={
presets:{
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
There is a lot of useful information on this subject here
Functions can have a name, which if specified cannot be changed. Functions can also be assigned to variables like any other object in javascript.
The first example is of a function declaration:
function myfunc(){
}
Using the function declaration you will be able to call the function from anywhere within the closure in which the function is declared, even if it is declared after it is used.
The other two examples are function expressions:
var myvar = function(){
/*some code*/
}
var SqueezeBox= {
presets: {
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
Using function expressions you are assigning functions to a variable. When doing this you must declare them before you use them. Most of the time you see this the functions will be anonymous but it is possible to name a function in an expression:
var myvar = function myFunc(){
myFunc(); // Because it has a name you can now call it recursively
}
When doing this, the myFunc function is only available within the body of the function because it is still a function expression rather than a declaration.
The third example declares a javascript object literal, SqueezeBox and within that object there is another called presets. Within this object there are two more objects/labels called onOpen and onClose. This means you can do the following to use these functions:
SqueezeBox.presets.onOpen();
SqueezeBox.presets.onClose();
You can think of onOpen and onClose as variables that are part of the object. So it's very similar to doing the following (but the variable is only in the scope of the presets object which is only available within the SqueezeBox object).
var onOpen = function() {};
This has already been answered here: What is the difference between a function expression vs declaration in Javascript?.
For the last example, as Atropo said, it's affecting an anonymous function to an object. It's similar to the var example.
JS newbie here, I've been looking through some code recently which uses syntax I'm not too familiar with. Here's an example, followed by my questions:
function Group(args) {
this.showItem = showItem;
function showItem(args) {
...
}
}
var group = new Group (args);
Questions:
As I understand it creating function Group and then instantiating via group = new Group is essentially prototypal equivalent of defining a class and then instantiating an object of that class. Is that correct?
Regarding the properties (methods?) of Group, what is the above syntax for showItem called? Why not just define it like:
this.showItem = function(args){...};
Would changing the code to the above change any different behavior?
If you did define it as above, what is that syntax called?
The Group function is being used as a constructor; your intuition is basically correct.
There is no good reason not to use an anonymous function expression like this.showItem = function(args){...};, unless you wanted to reuse the local variable showItem.
I'm not sure which syntax you mean. The function(args){...} is an anonymous function expression, and the this.showItem is referring to a member of the object this. Taken all together, I suppose you could call it "setting a member function of an object".
Bonus tip (which maybe you already knew?): the reason you can use showItem before its definition is due to function hoisting.
EDIT:
You seem to be asking about function expressions versus function declarations as well as named versus anonymous functions. The primary differences are:
Function declarations always stand on their own. They are never part of another operation, e.g. assignment. Your first example uses the function declaration function showItem(args) {...}. Function expressions are used as an expression in some operation (e.g., assignment, passed as an argument, etc.). Your second case uses a function expression.
Function declarations are hoisted to the top of the current function scope, so showItem in your first case is defined and contains the function when you use it in your assignment operation. Function expressions are not hoisted.
Function declarations are always named. Function expressions may be named or anonymous. When a function is defined with a name, that name is accessible as the name property of the function object. A function's name is immutable and independent of any variables that hold a reference to the function. Also, code inside the function body can refer to the function by its name as a local variable (which is sometimes useful for recursion inside named function expressions).
To review:
Function definition: function showItems(args){...};
Anonymous function expression: this.showItems = function(args){...};
Named function expression: this.showItems = function showItemsName(args){...};
In the first case, there is a local variable called showItems defined and the definition of showItems is hoisted to the top. The difference between the latter two cases is that this.showItems.name will be "showItemsName" for the third case and undefined for the second. Also, showItemsName will be a local variable within the function body of the third function that holds a reference to the function object.
The Group function is used as a constructor. However, the way this is done is a bit inefficient. What this code is doing is creating a new function and attaching it to the constructed object. He may be doing this because he wants to create a closure (i.e. use a variable only present in the namespace of the constructor), but absent that reason it's better to do this:
function Group(args){}
Group.prototype.showItem = function(args) {};
This way the same showItem function is shared among all objects constructed by Group via the prototype chain.
The benefit of using the original code vs an anonymous function is that the function has a name--this is a great help in debugging because reading a traceback full of anonymous function calls is no fun! To expand, there are three types of things that use the function keyword:
Function declarations When at the top level of a program or a function (i.e., of something that creates/has its own namespace), you may declare a function with a name. (The name stays with the function object throughout the program and will appear in tracebacks.) This is function showItem(args) {} in your example. (Note that this is only a function declaration at the top level of a file or function. There's a very similar thing I'll get to last.) By convention most people seem to omit semicolons after these.
Function expressions When part of an expression (such as assignment, return, etc), it is a function expression. The identifier part of the function expression is optional, so these are both function expressions:
var myfunc1 = function(){};
var myfunc2 = function MyFunctionName(){};
The second form is called a "named function expression". The great benefit of using this form is that MyFunctionName is no longer an anonymous function--this name will be attached to the function and will show up in tracebacks (for example). However there is a very serious bug in JScript (IE <= 8) that makes using these problematic. Read the article I linked above for details.
Finally, there is a common extension syntax called function statements. These look exactly like function declarations, except they are not top level! For example:
function() {
function foo(){} // function declaration
if (1) {
function bar(){} // function STATEMENT--not standard JS!
}
}
You should not rely on this extension, but should do this instead:
function() {
var bar;
if (1) {
bar = function bar(){};
}
}
this.showItem = function(){} would be called a "function expression in an assignment", and the original code is just using a "function declaration".
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do var fn = function() {…} and var fn = function foo() {…} ever differ?
From here
What is the difference between a function expression vs declaration in JavaScript?
I understand that there is a difference between declaring functions and declaring them as variables.
But It's not clear if there is any difference between:
var func_name = function(param, param1){...};
and:
var func_name = function func_name(param, param1){...};
Are they exactly identical?
There are 2 ways of declaring a function in JavaScript.
Function Declaration
Functions declarations are statements so they begin with the function keyword and you have to give the function a name.
These are also parsed before code execution starts, so the code below would not throw an error:
foo(); // "foo" exists because it was created at parse time
function foo() {
}
Function Expressions
Function expressions are - as the name states - expressions. Functions in
expressions are treated like any other value (e.g. numbers, strings etc.) and
naming them is purely optional.
Functions from expressions are created at runtime, so the code below will
throw an expection:
foo(); // "foo" does not exist yes because it will not be created until the line below is executed
var foo = function() {
}
Function names
Functions names are mainly good two things.
Calling function declarations
Accessing the function object from within the function
As stated, in case of expressions the name can be left out; thus, creating a so called anonymous function
So in your example you got two function expressions, one of which is a anonymous function and the other is not.
See also: http://bonsaiden.github.com/JavaScript-Garden/#function.general
the answer is "no".
You can always call the function by its name inside the function.
var func_name = function other_0func_name(param, param1){
..... ;
other_func_name()};
I'm pretty sure that's only used to make debugging easier.
It appears that named functions make for a much more pleasant debugging experience. When debugging an application, having a call stack with descriptive items makes a huge difference.
var func_name = function(param, param1){...};
will create an anonymous function and assign to the variable "func_name"
var func_name = function func_name(param, param1){...};
will create a function named "func_name" and then assign that function to the variable "func_name"
If you test these two lines in the console, you will see
var func_name = function(param, param1){};
console.log(func_name)
will give
function (param, param1){}
whereas
var func_name = function func_name(param, param1){};
console.log(func_name)
will give
function func_name(param, param1){}
There will be no difference in terms of usage so for your purposes they are the same.
Hope this clears it up.