Javascript object variables and functions

First question

var obj = function(){  
    var a = 0;  
    this.b = 0; 
}

Is there a difference in behavior aand b?


Second question

var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert('+x+')')

Is there a difference in behavior f1andf2

+5
source share
6 answers

Question 1

var obj = function() {
   var a = 0;
   this.b = 0;
}

Inside the function, you can access both variables, but in the case of

var x = new obj();

... you can access x.b, but not x.a.

Question 2

Since your question is currently written, this is a syntax error. The following will work:

var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert('+x+')')

... but it will be the same as the entry:

var x = 'a';
var f1 = function(x){ alert(x) }
var f2 = new Function('alert(a)')

. f1 x , , f2 x a. , , .

, , , :

var x = 'a';
var f1 = function(){ alert(x) }
var f2 = new Function('alert(x)')

... :

var f1 = function(x){ alert(x) }
var f2 = new Function('x', 'alert(x)')

, x, . f1 f2, , .

. , - f2, , , . , .

+5
var obj = function() { // function expression, while obj is created before head
                       // it only assigned the anonymous function at runtime
     var a = 0; // variable local to the scope of this function
     this.b = 0; // sets a property on 'this'
}

, this , .

.

var x = 'a'; // string a, woah!
var f1 = function(x){ alert(x) } // another anonymous function expression

// Does not work
// 1. it "Function"
// 2. It gets evaluated in the global scope (since it uses eval)
// 3. It searches for 'a' in the global scope
var f2 = new function('alert('+x+')') // function constructor

, Function, , closures ..

+4

:

 var obj = function() {
    var a = 0;
    this.b = 0;
 }

 instance = new obj();

 instance.showA = function() {
    alert("this.a = " + this.a);
 }

 instance.showB = function() {
    alert("this.b = " + this.b);
 }

 instance.showA();   // output undefined - local scope only, not even to methods.
 instance.showB();   // output 0 - accessible in method

Firebug , .

:

  var f2 = new function('alert('+x+')');

Firebug, f . , . :

  var x = 'a=3';
  var f2 = new Function('alert('+x+')');

  f2();   // outputs 3 because the x passed into the variable is evaluated and becomes nested inside the quotes prior to the alert command being fired.

:

  1:  x = "a=3";    
  2:  'alert(' + x + ')');
  3:  'alert(' + 'a=3' + ')');    // x replaced with a=3
  4:  'alert(a=3)';
  5:  'alert(3);'

, (3). JavaScript, , . , , . : http://blog.opensourceopportunities.com/2007/10/nested-nested-quotes.html

+1

1: (var b {} ( ).

2: Function eval? http://www.w3schools.com/jsref/jsref_eval.asp,

eval 'alert('+x+')';
0

question # 1: both are installed locally, but b needs to be called using function .b question No. 2: I don't believe f2 will work ...

-1
source

All Articles