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
Question 1
Within the function, you’ll be able to access both variables, but in the case of
… you’ll be able to access
x.b, but notx.a.Question 2
As your question is written at the moment, it is a syntax error. The following will work:
… but that would be the same thing as writing:
The difference here is obvious.
f1disregards the global variablexand alerts whatever is passed to it, whilef2also disregards the global variablex, and tries to look for a global variablea. This is probably not what you’re trying to ask about.What you probably want is something like this:
… or this:
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 betweenf1andf2, 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
f2approach would be when generating the code in some dynamic manner that require string input for its definition. In general, try to avoid this practice.