Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object variables and functions

Tags:

javascript

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

like image 950
Dan Avatar asked Jan 11 '11 08:01

Dan


People also ask

What are variables and objects in JavaScript?

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(){}

Can JavaScript objects have functions?

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.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

Question 1

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.

Question 2

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.

like image 111
David Hedlund Avatar answered Sep 25 '22 03:09

David Hedlund