What's the difference in closure style - javascript

There are two popular closure styles in javascript. The first I call anonymous constructor:
new function() {
var code...
}
and the inline executed function:
(function() {
var code...
})();
are there differences in behaviour between those two? Is one "better" over the other?

Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function.
Basically behaviour of
new expression
Is effectively equivalent to
var tempObject = {};
var result = expression.call(tempObject);
if (result is not an object)
result = tempObject;
Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check.
Broadly speaking the "new function() { .. }" method will be slower due to the need to create the this object for the constructor.
That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure).
Edit: one thing i realised that i missed from this is that the tempObject will get expressions prototype, eg. (before the expression.call) tempObject.__proto__ = expression.prototype

#Lance: the first one is also executing. Compare it with a named constructor:
function Blah() {
alert('blah');
}
new Bla();
this is actually also executing code. The same goes for the anonymous constructor...
But that was not the question ;-)

They both create a closure by executing the code block. As a matter of style I much prefer the second for a couple of reasons:
It's not immediately obvious by glancing at the first that the code will actually be executed; the line looks like it is creating a new function, rather than executing it as a constructor, but that's not what's actually happening. Avoid code that doesn't do what it looks like it's doing!
Also the (function(){ ... })(); make nice bookend tokens so that you can immediately see that you're entering and leaving a closure scope. This is good because it alerts the programmer reading it to the scope change, and is especially useful if you're doing some postprocessing of the file, eg for minification.

Well, I made a page like this:
<html>
<body>
<script type="text/javascript">
var a = new function() {
alert("method 1");
return "test";
};
var b = (function() {
alert("method 2");
return "test";
})();
alert(a); //a is a function
alert(b); //b is a string containing "test"
</script>
</body>
</html>
Surprisingly enough (to me anyway) it alerted both "method 1" and method 2". I didn't expect "method 1" to be alerted. The difference was what the values of a and b were. a was the function itself, while b was the string that the function returned.

Yes, there are differences between the two.
Both are anonymous functions and execute in the exact same way. But, the difference between the two is that in the second case scope of the variables is restricted to the anonymous function itself. There is no chance of accidentally adding variables to the global scope.
This implies that by using the second method, you are not cluttering up the global variables scope which is good as these global variable values can interfere with some other global variables that you may use in some other library or are being used in a third party library.
Example:
<html>
<body>
<script type="text/javascript">
new function() {
a = "Hello";
alert(a + " Inside Function");
};
alert(a + " Outside Function");
(function() {
var b = "World";
alert(b + " Inside Function");
})();
alert(b + " Outside Function");
</script>
</body>
</html>
In the above code the output is something like:
Hello Inside Function
Hello Outside Function
World Inside Function
... then, you get an error as 'b' is not defined outside the function!
Thus, I believe that the second method is better... safer!

Related

JavaScript completely wrapping ()? [duplicate]

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.
(function() {
...
code
...
})();
What is the reason for doing this rather than a simple set of constructor functions?
It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. The technical name for it is an Immediately Invoked Function Expression (IIFE). jQuery plugins are usually written like this.
In Javascript, you can nest functions. So, the following is legal:
function outerFunction() {
function innerFunction() {
// code
}
}
Now you can call outerFunction(), but the visiblity of innerFunction() is limited to the scope of outerFunction(), meaning it is private to outerFunction(). It basically follows the same principle as variables in Javascript:
var globalVariable;
function someFunction() {
var localVariable;
}
Correspondingly:
function globalFunction() {
var localFunction1 = function() {
//I'm anonymous! But localFunction1 is a reference to me!
};
function localFunction2() {
//I'm named!
}
}
In the above scenario, you can call globalFunction() from anywhere, but you cannot call localFunction1 or localFunction2.
What you're doing when you write (function() { ... })(), is you're making the code inside the first set of parentheses a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()) that you just defined. So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:
(function() {
var private_var;
function private_function() {
//code
}
})();
In the first example, you would explicitly invoke globalFunction by name to run it. That is, you would just do globalFunction() to run it. But in the above example, you're not just defining a function; you're defining and invoking it in one go. This means that when the your JavaScript file is loaded, it is immediately executed. Of course, you could do:
function globalFunction() {
// code
}
globalFunction();
The behavior would largely be the same except for one significant difference: you avoid polluting the global scope when you use an IIFE (as a consequence it also means that you cannot invoke the function multiple times since it doesn't have a name, but since this function is only meant to be executed once it really isn't an issue).
The neat thing with IIFEs is that you can also define things inside and only expose the parts that you want to the outside world so (an example of namespacing so you can basically create your own library/plugin):
var myPlugin = (function() {
var private_var;
function private_function() {
}
return {
public_function1: function() {
},
public_function2: function() {
}
}
})()
Now you can call myPlugin.public_function1(), but you cannot access private_function()! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:
Namespacing your Javascript
Private members in Javascript (by Douglas Crockford)
EDIT
I forgot to mention. In that final (), you can pass anything you want inside. For example, when you create jQuery plugins, you pass in jQuery or $ like so:
(function(jQ) { ... code ... })(jQuery)
So what you're doing here is defining a function that takes in one parameter (called jQ, a local variable, and known only to that function). Then you're self-invoking the function and passing in a parameter (also called jQuery, but this one is from the outside world and a reference to the actual jQuery itself). There is no pressing need to do this, but there are some advantages:
You can redefine a global parameter and give it a name that makes sense in the local scope.
There is a slight performance advantage since it is faster to look things up in the local scope instead of having to walk up the scope chain into the global scope.
There are benefits for compression (minification).
Earlier I described how these functions run automatically at startup, but if they run automatically who is passing in the arguments? This technique assumes that all the parameters you need are already defined as global variables. So if jQuery wasn't already defined as a global variable this example would not work. As you might guess, one things jquery.js does during its initialization is define a 'jQuery' global variable, as well as its more famous '$' global variable, which allows this code to work after jQuery has been included.
In short
Summary
In its simplest form, this technique aims to wrap code inside a function scope.
It helps decreases chances of:
clashing with other applications/libraries
polluting superior (global most likely) scope
It does not detect when the document is ready - it is not some kind of document.onload nor window.onload
It is commonly known as an Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.
Code Explained
var someFunction = function(){ console.log('wagwan!'); };
(function() { /* function scope starts here */
console.log('start of IIFE');
var myNumber = 4; /* number variable declaration */
var myFunction = function(){ /* function variable declaration */
console.log('formidable!');
};
var myObject = { /* object variable declaration */
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
})(); /* function scope ends */
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
In the example above, any variable defined in the function (i.e. declared using var) will be "private" and accessible within the function scope ONLY (as Vivin Paliath puts it). In other words, these variables are not visible/reachable outside the function. See live demo.
Javascript has function scoping. "Parameters and variables defined in a function are not visible outside of the function, and that a variable defined anywhere within a function is visible everywhere within the function." (from "Javascript: The Good Parts").
More details
Alternative Code
In the end, the code posted before could also be done as follows:
var someFunction = function(){ console.log('wagwan!'); };
var myMainFunction = function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
};
myMainFunction(); // I CALL "myMainFunction" FUNCTION HERE
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
See live demo.
The Roots
Iteration 1
One day, someone probably thought "there must be a way to avoid naming 'myMainFunction', since all we want is to execute it immediately."
If you go back to the basics, you find out that:
expression: something evaluating to a value. i.e. 3+11/x
statement: line(s) of code doing something BUT it does not evaluate to a value. i.e. if(){}
Similarly, function expressions evaluate to a value. And one consequence (I assume?) is that they can be immediately invoked:
var italianSayinSomething = function(){ console.log('mamamia!'); }();
So our more complex example becomes:
var someFunction = function(){ console.log('wagwan!'); };
var myMainFunction = function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
}();
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
See live demo.
Iteration 2
The next step is the thought "why have var myMainFunction = if we don't even use it!?".
The answer is simple: try removing this, such as below:
function(){ console.log('mamamia!'); }();
See live demo.
It won't work because "function declarations are not invokable".
The trick is that by removing var myMainFunction = we transformed the function expression into a function declaration. See the links in "Resources" for more details on this.
The next question is "why can't I keep it as a function expression with something other than var myMainFunction =?
The answer is "you can", and there are actually many ways you could do this: adding a +, a !, a -, or maybe wrapping in a pair of parenthesis (as it's now done by convention), and more I believe. As example:
(function(){ console.log('mamamia!'); })(); // live demo: jsbin.com/zokuwodoco/1/edit?js,console.
or
+function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wuwipiyazi/1/edit?js,console
or
-function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wejupaheva/1/edit?js,console
What does the exclamation mark do before the function?
JavaScript plus sign in front of function name
So once the relevant modification is added to what was once our "Alternative Code", we return to the exact same code as the one used in the "Code Explained" example
var someFunction = function(){ console.log('wagwan!'); };
(function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
})();
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
Read more about Expressions vs Statements:
developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Function_constructor_vs._function_declaration_vs._function_expression
Javascript: difference between a statement and an expression?
Expression Versus Statement
Demystifying Scopes
One thing one might wonder is "what happens when you do NOT define the variable 'properly' inside the function -- i.e. do a simple assignment instead?"
(function() {
var myNumber = 4; /* number variable declaration */
var myFunction = function(){ /* function variable declaration */
console.log('formidable!');
};
var myObject = { /* object variable declaration */
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
myOtherFunction = function(){ /* oops, an assignment instead of a declaration */
console.log('haha. got ya!');
};
})();
myOtherFunction(); // reachable, hence works: see in the console
window.myOtherFunction(); // works in the browser, myOtherFunction is then in the global scope
myFunction(); // unreachable, will throw an error, see in the console
See live demo.
Basically, if a variable that was not declared in its current scope is assigned a value, then "a look up the scope chain occurs until it finds the variable or hits the global scope (at which point it will create it)".
When in a browser environment (vs a server environment like nodejs) the global scope is defined by the window object. Hence we can do window.myOtherFunction().
My "Good practices" tip on this topic is to always use var when defining anything: whether it's a number, object or function, & even when in the global scope. This makes the code much simpler.
Note:
javascript does not have block scope (Update: block scope local variables added in ES6.)
javascript has only function scope & global scope (window scope in a browser environment)
Read more about Javascript Scopes:
What is the purpose of the var keyword and when to use it (or omit it)?
What is the scope of variables in JavaScript?
Resources
youtu.be/i_qE1iAmjFg?t=2m15s - Paul Irish presents the IIFE at min 2:15, do watch this!
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Book: Javascript, the good parts - highly recommended
youtu.be/i_qE1iAmjFg?t=4m36s - Paul Irish presents the module pattern at 4:36
Next Steps
Once you get this IIFE concept, it leads to the module pattern, which is commonly done by leveraging this IIFE pattern. Have fun :)
Javascript in a browser only really has a couple of effective scopes: function scope and global scope.
If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.
That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.
Example. Suppose I write:
(function() {
var x = 2;
// do stuff with x
})();
Now other libraries cannot access the variable x I created to use in my library.
You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.
navigator.html5={
canvas: (function(){
var dc= document.createElement('canvas');
if(!dc.getContext) return 0;
var c= dc.getContext('2d');
return typeof c.fillText== 'function'? 2: 1;
})(),
localStorage: (function(){
return !!window.localStorage;
})(),
webworkers: (function(){
return !!window.Worker;
})(),
offline: (function(){
return !!window.applicationCache;
})()
}
In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:
(function($) { ...code...})(jQuery);
To avoid clash with other methods/libraries in the same window,
Avoid Global scope, make it local scope,
To make debugging faster (local scope),
JavaScript has function scope only, so it will help in compilation of codes as well.
We should also use 'use strict' in the scope function to make sure that the code should be executed in "strict mode". Sample code shown below
(function() {
'use strict';
//Your code from here
})();
Provide an example for the accepted answer, from https://requirejs.org/docs/whyamd.html:
(function () {
var $ = this.jQuery;
this.myExample = function () {};
}());
The code demonstrates that we can:
use global variables inside the scope
export functions, variables etc.. by binding on this, which is the window object as for browsers.
Its called encapsulation in OOP.

Peculiar JavaScript construct: variable of object type in object definition

Okay, I stumbled upon this piece of code..
How come this works? What sort of evil scheme does JavaScript use to resolve variables?
The way I see it, as a C++ kind of guy: the class/object definition contains a non-existent reference to an object of the class being defined. Seriously, how?
(To be honest, I understand partially - I could deduce a strawman concept of how and when JS resolves names.. but maybe this way the question will be of more use to someone else, someday)
Guilty code:
function Sio() {
this.someValue = 5;
this.doStuff = function() {
console.log("look: "+howDoYouResolveThisYouFoulCreature.someValue);
};
}
var howDoYouResolveThisYouFoulCreature = new Sio();
That seems so wrong.
Lots of concepts here, and I'm not sure which one is giving you troubles…
The two most likely ones are new / this and var.
new / this
When you call a function the value of this is determined by the context in which you call it.
If you use the new keyword, you create an instance of the function and make that instance the context.
When you call howDoYouResolveThisYouFoulCreature.doStuff() you are accessing that instance as a global. It would usually make more sense to:
this.doStuff = function() {
console.log("look: "+ this.someValue);
};
Since foo.doStuff() makes foo the context for that invokation of doStuff() (which makes the function reusable between different instances of Sio)
var
Scope in JavaScript is at the function level.
Using var something anywhere inside a function will scope that variable to that function
It is considered good practise to use a single var statement at the top of a function to avoid confusion
Also, the doStuff function is not called before howDoYouResolveThisYouFoulCreature has a value. Until that point all that matters is that the function is syntactically correct, it doesn't matter what type the variable is.
It works because the function() this.doStuff isn't executed before howDoYouResolveThisYouFoulCreature is created. Keep in mind for as many new Sio()'s that you make this will always console.log the howDoYouResolveThisYouFoulCreature.someValue regardless of the variable name that doStuff() is called from.
This works because:
var howDoYouResolveThisYouFoulCreature = new Sio();
... actually resolves into:
var howDoYouResolveThisYouFoulCreature;
howDoYouResolveThisYouFoulCreature = new Sio();
So at the time the function doStuff is assigned, the var is already declared.
Edit: Forget that, I was being foolish. It turns out pimvdb is right, and here's the proof (also on jsfiddle):
function A() {
this.logValue = function() {
if (b === undefined) {
console.log('Wah, wah, wah...');
} else {
console.log(b.someValue);
}
};
}
function B() {
this.someValue = 42;
}
var a = new A();
a.logValue(); // Wah, wah, wah...
var b = new B();
a.logValue(); // 42
So the execution context is the key. When Sio (or, in this case, A) is constructed, it's scoped to where b might, at some point, be defined. The variable isn't resolved until the function is called, at which point it might be defined. Or not. No biggie. :-)

Difference between these two types of self executing function on JavaScript

I always use the following self executing function in order to avoid exposing my code to global scope in JavaScript:
(function() {
//Code comes here
})();
I believe that this is also called self executing anonymous function as well. Sometimes, I also see the below code used for the same purpose:
(function(d){
//Code comes here
})(document.documentElement);
I am not sure what makes the difference here so I am asking this question.
What is the difference (or are the differences) between these two types of self executing function on JavaScript?
The code below demonstrates what's happening. In reality, the foo and bar variables don't exist, and the functions are anonymous.
var foo = function() {}
foo();
var bar = function(d){}
bar(document.documentElement);
The (function(d){})(d) method is called a closure. It's used to pass variable values which are subject to change, such as in loops.
Have a look at a practical an example:
for(var i=0; i<10; i++) {
document.links[i].onclick = function(){
alert(i); //Will always alert 9
}
}
After implementing the closure:
for(var i=0; i<10; i++) {
(function(i){
document.links[i].onclick = function(){
alert(i); //Will alert 0, 1, ... 9
}
})(i);
}
Remember that function arguments and variables are the same thing, deep down.
The second example is (basically) just shorthand for
(function(){
var d = document.documentElement;
}());
since it avoids the need for the var and the =.
There are some common uses for this pattern:
Creating lexically scoped variables (just remembered this after seeing Rob's answer...)
//this does not work because JS only has function scope.
// The i is shared so all the onclicks log N instead of the correct values
for(var i = 0; i< N; i++){
elems[i].onclick = function(){ console.log(i); }
}
//Each iteration now gets its own i variable in its own function
// so things work fine.
for(var i=0; i<N; i++){
(function(i){
elems[i].onclick = function{ console.log(i); };
}(i));
}
In this case, passing the parameters directly allows us to reuse the same variable name inside, in a way that var i = i would not be able to. Also, the conciseness is a benefit, since this is just a boilerplate pattern that we don't want to dominate over the important code around it.
It makes it easy to convert some old code without having to think too much about it
(function($){
//lots of code that expected $ to be a global...
}(jQuery)) //and now we can seamlessly do $=jQuery instead.
Parameters that are not passed are set to undefined. This is useful since normally undefined is just a global variable that can be set to different values (this is specially important if you are writing a library that needs to work w/ arbitrary third party scripts)
(function(undefined){
//...
}())
The first function takes no parameters. The second one takes a single parameter. Inside the function, the parameter is d. d is set to document.documentElement when the function is called.
It looks like the author of the second code wants to use d as a shorter way to write document.documentElement inside the function.
if you want to pass arguments to the self executing anonymous functions, use the second one. It might come in handy when you want to use variables in the function that have the same name with others in the global scope :
var a = "I'm outside the function scope",
b = 13;
alert(a);
alert(b);
(function(a,b){
// a is different from the initial a
alert(a);
// same goes for b
alert(b);
})("I'm inside the function scope",Math.PI);
It can also be useful to use something like :
var a;
console.log(a === undefined); // true
undefined = true;
console.log(a === undefined); // false
(function(undefined){
console.log(a === undefined); // true, no matter what value the variable "undefined" has assigned in the global scope
})();
when trying to implement the null object design pattern
If you are concerned about efficiency, you might end up using something like this :
var a = 2;
(function(window){
alert(a);
// accessing a from the global scope gets translated
// to something like window.a, which is faster in this particular case
// because we have the window object in the function scope
})(window);
One reason for using the second form, with the argument, is that insulates your code against other js code loaded later on the page (eg other libraries or framework code) that might re-define the variable passed in as the argument.
One common example would be if the code within your self-executing anonymous function relies upon jQuery and wants to use the $ variable.
Other js frameworks also define the $ variable. If you code your function as:
(function($){
//Code comes here
})(jQuery);
Then you can safely use $ for jQuery even if you load some other library that defines $.
I have seen this used defensively with people passing in all the 'global' variables they need inside their block, such as window, document, jQuery/$ etc.
Better safe than sorry, especially if you use a lot of 3rd party widgets and plugins.
Update:
As others have pointed out the set of parentheses around the function are a closure. They are not strictly neccessary a lot of times where this pattern is used (#Rob W gives a good example where they're essential) but say you have a very long function body... the outer parentheses say to others reading the code that the function is probably self-executing.
Best explanation I saw of this pattern is in Paul Irish's video here: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/ starting about 1:30
This SO question also has some informative answers: How do you explain this structure in JavaScript?

Trouble using 'eval' to define a toplevel function when called from within an object

I've written (in JavaScript) an interactive read-eval-print-loop that is encapsulated
within an object. However, I recently noticed that toplevel function definitions specified to the interpreter do not appear to be 'remembered' by the interpreter. After some diagnostic work, I've reduced the core problem to this:
var evaler = {
eval: function (str)
{
return eval(str);
},
};
eval("function t1() { return 1; }"); // GOOD
evaler.eval("function t2() { return 2; }"); // FAIL
At this point, I am hoping that the following two statements wil work as expected:
print(t1()); // => Results in 1 (This works)
print(t2()); // => Results in 2 (this fails with an error that t2 is undefined.)
What I get instead is the expected value for the t1 line, and the t2 line fails with an error that t2 is unbound.
IOW: After running this script, I have a definition for t1, and no defintion for t2. The act of calling eval from within evaler is sufficiently different from the toplevel call that the global definition does not get recorded. What does happen is that the call to
evaler.eval returns a function object, so I'm presuming that t2 is being defined and stored in some other set of bindings that I don't have access to. (It's not defined as a member in evaler.)
Is there any easy fix for this? I've tried all sorts of fixes, and haven't stumbled upon one that works. (Most of what I've done has centered around putting the call to eval in an anonymous function, and altering the way that's called, chainging __parent__, etc.)
Any thoughts on how to fix this?
Here's the result of a bit more investigation:
tl;dr: Rhino adds an intermediate scope to the scope chain when calling a method on an instance. t2 is being defined in this intermediate scope, which is immediately discarded. #Matt: Your 'hacky' approach might well be the best way to solve this.
I'm still doing some work on the root cause, but thanks to some quality time with jdb, I now have more understanding of what's happening. As has been discussed, a function statement like function t1() { return 42; } does two things.
It creates an anonymous instance of a function object, like you'd get with the expression function() { return 42; }
It binds that anonymous function to the current top scope with the name t1.
My initial question is about why I'm not seeing the second of these things happen when I call eval from within a method of an object.
The code that actually performs the binding in Rhino appears to be in the function org.mozilla.javascript.ScriptRuntime.initFunction.
if (type == FunctionNode.FUNCTION_STATEMENT) {
....
scope.put(name, scope, function);
For the t1 case above, scope is what I've set to be my top-level scope. This is where I want my toplevel functions defined, so this is an expected result:
main[1] print function.getFunctionName()
function.getFunctionName() = "t1"
main[1] print scope
scope = "com.me.testprogram.Main#24148662"
However, in the t2 case, scope is something else entirely:
main[1] print function.getFunctionName()
function.getFunctionName() = "t2"
main[1] print scope
scope = "org.mozilla.javascript.NativeCall#23abcc03"
And it's the parent scope of this NativeCall that is my expected toplevel scope:
main[1] print scope.getParentScope()
scope.getParentScope() = "com.me.testprogram.Main#24148662"
This is more or less what I was afraid of when I wrote this above: " In the direct eval case, t2 is being bound in the global environment. In the evaler case, it's being bound 'elsewhere'" In this case, 'elsewhere' turns out to be the instance of NativeCall... the t2 function gets created, bound to a t2 variable in the NativeCall, and the NativeCall goes away when the call to evaler.eval returns.
And this is where things get a bit fuzzy... I haven't done as much analysis as I'd like, but my current working theory is that the NativeCall scope is needed to ensure that this points to evaler when execution in the call to evaler.eval. (Backing up the stack frame a bit, the NativeCall gets added to the scope chain by Interpreter.initFrame when the function 'needs activation' and has a non-zero function type. I'm assuming that these things are true for simple function invocations only, but haven't traced upstream enough to know for sure. Maybe tomorrow.)
Your code actually is not failing at all. The eval is returning a function which you never invoke.
print(evaler.eval("function t2() { return 2; }")()); // prints 2
To spell it out a bit more:
x = evaler.eval("function t2() { return 2; }"); // this returns a function
y = x(); // this invokes it, and saves the return value
print(y); // this prints the result
EDIT
In response to:
Is there another way to create an interactive read-eval-print-loop than to use eval?
Since you're using Rhino.. I guess you could call Rhino with a java Process object to read a file with js?
Let's say I have this file:
test.js
function tf2() {
return 2;
}
print(tf2());
Then I could run this code, which calls Rhino to evaluate that file:
process = java.lang.Runtime.getRuntime().exec('java -jar js.jar test.js');
result = java.io.BufferedReader(java.io.InputStreamReader(process.getInputStream()));
print(result.readLine()); // prints 2, believe it or not
So you could take this a step further by WRITING some code to eval to a file, THEN calling the above code ...
Yes, it's ridiculous.
The problem you are running into is that JavaScript uses function level scoping.
When you call eval() from within the eval function you have defined, it is probably creating the function t2() in the scope of that eval: function(str) {} function.
You could use evaler.eval('global.t2 = function() { return 2; }'); t2();
You could also do something like this though:
t2 = evaler.eval("function t2() { return 2; }");
t2();
Or....
var someFunc = evaler.eval("function t2() { return 2; }");
// if we got a "named" function, lets drop it into our namespace:
if (someFunc.name) this[someFunc.name] = someFunc;
// now lets try calling it?
t2();
// returns 2
Even one step further:
var evaler = (function(global){
return {
eval: function (str)
{
var ret = eval(str);
if (ret.name) global[ret.name] = ret;
return ret;
}
};
})(this);
evaler.eval('function t2() { return 2; }');
t2(); // returns 2
With the DOM you could get around this function-level scoping issue by injecting "root level" script code instead of using eval(). You would create a <script> tag, set its text to the code you want to evaluate, and append it to the DOM somewhere.
Is it possible that your function name "eval" is colliding with the eval function itself? Try this:
var evaler = {
evalit: function (str)
{
return window.eval(str);
},
};
eval("function t1() { return 1; }");
evaler.evalit("function t2() { return 2; }");
Edit
I modified to use #Matt's suggestion and tested. This works as intended.
Is it good? I frown on eval, personally. But it works.
I think this statement:
evaler.eval("function t2() { return 2; }");
does not declare function t2, it just returns Function object (it's not function declaration, it's function operator), as it's used inside an expression.
As evaluation happens inside function, scope of newly created function is limited to evaler.eval scope (i.e. you can use t2 function only from evaler.eval function):
js> function foo () {
eval ("function baz() { return 'baz'; }");
print (baz);
}
js> foo ();
function baz() {
return "baz";
}
js> print(baz);
typein:36: ReferenceError: baz is not defined
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/operators/special_operators/function_operator.html
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/statements/function.html
I got this answer from the Rhino mailing list, and it appears to work.
var window = this;
var evaler = {
eval : function (str) {
eval.call(window, str);
}
};
The key is that call explicitly sets this, and this gets t2 defined in the proper spot.

How do you explain this structure in JavaScript?

(function()
{
//codehere
}
)();
What is special about this kind of syntax?
What does ()(); imply?
The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
function name (){...}
name();
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.
It's an anonymous function being called.
The purpose of that is to create a new scope from which local variables don't bleed out. For example:
var test = 1;
(function() {
var test = 2;
})();
test == 1 // true
One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.
The snippet below will cause an error:
var aVariable = 1
var myVariable = aVariable
(function() {/*...*/})()
Here's what it's actually doing:
var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();
Another way of creating a new block scope is to use the following syntax:
new function() {/*...*/}
The difference is that the former technique does not affect where the keyword "this" points to, whereas the second does.
Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.
That is a self executing anonymous function. The () at the end is actually calling the function.
A good book (I have read) that explains some usages of these types of syntax in Javascript is Object Oriented Javascript.
This usage is basically equivalent of a inner block in C. It prevents the variables defined inside the block to be visible outside. So it is a handy way of constructing a one off classes with private objects. Just don't forget return this; if you use it to build an object.
var Myobject=(function(){
var privatevalue=0;
function privatefunction()
{
}
this.publicvalue=1;
this.publicfunction=function()
{
privatevalue=1; //no worries about the execution context
}
return this;})(); //I tend to forget returning the instance
//if I don't write like this
See also Douglas Crockford's excellent "JavaScript: The Good Parts," available from O'Reilly, here:
http://oreilly.com/catalog/9780596517748/
... and on video at the YUIblog, here:
http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/
The stuff in the first set of brackets evaluates to a function. The second set of brackets then execute this function. So if you have something that want to run automagically onload, this how you'd cause it to load and execute.
John Resig explains self-executing anonymous functions here.

Categories

Resources