First question
var obj = function(){
var a = 0;
this.b = 0;
}
Is there any difference in behaviour of a
and b
?
Second question
var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert('+x+')')
Is there any difference in behaviour of f1
and f2
A variable object is simply an object storing data related to an execution context. The data includes variables and function declarations defined in the context. Let's consider the following example: function foo(){ var a = 20; function bar(){}
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
var obj = function() {
var a = 0;
this.b = 0;
}
Within the function, you'll be able to access both variables, but in the case of
var x = new obj();
... you'll be able to access x.b
, but not x.a
.
As your question is written at the moment, it is a syntax error. The following will work:
var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert('+x+')')
... but that would be the same thing as writing:
var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert(a)')
The difference here is obvious. f1
disregards the global variable x
and alerts whatever is passed to it, while f2
also disregards the global variable x
, and tries to look for a global variable a
. This is probably not what you're trying to ask about.
What you probably want is something like this:
var x = 'a';
var f1 = function(){ alert(x) }
var f2 = new Function('alert(x)')
... or this:
var f1 = function(x){ alert(x) }
var f2 = new Function('x', 'alert(x)')
The difference between the two alternatives above is that the first always uses the global variable x
, while the second never uses any global variable. The difference between f1
and f2
, internally, in both examples, is none at all.
These are two ways of generating the exact same result. The only reason you'd ever want to use the f2
approach would be when generating the code in some dynamic manner that require string input for its definition. In general, try to avoid this practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With