Kevin Mogi
Kevin Mogi

Reputation: 117

Super Tricky Javascript quiz, need to figure out about the answer

   //1st question
   var x = 4,
     obj = {
       x: 3,
       bar: function() {
         var x = 2;
         setTimeout(function() {
           var x = 1;
           alert(this.x);
         }, 1000);
       }
     };
   obj.bar();

   //2nd question
   function foo(a) {
     arguments[0] = 2;
     alert(a);
   }
   foo(1);

1.why it returns 4 instead of 1? i thought this.x refer to 1, but it seems wrong....i just dont understand why it returns 4

2.why it return alert 2 instead of 1, i thought i pass a to function a, and as far as i know, i pass 1 to function foo, and 1 should be alerted because of a(which is 1 when i pass)....i just don't understand why it alert 2

Upvotes: 3

Views: 2876

Answers (2)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

1. why it returns 4 instead of 1?

Notice the first initialization: var x = 4, which in non-strict mode attaches a property x to global object: window.x = 4.

setTimeout(function() {
 var x = 1;
 alert(this.x);
}, 1000);

setTimout() callback has this context as the global object. And actually calling alert(this.x) -> alert(window.x) -> alert(4).

2.why it return alert 2 instead of 1

arguments object represents the list of function arguments. When modifying it, you actually modify the arguments values: arguments[0] = 2 modifies first argument a = 2.

Upvotes: 1

Pointy
Pointy

Reputation: 413737

  1. The runtime (in non-strict mode) invokes the setTimeout() callback with this bound to window (the global context), so this.x refers to the outer x.

  2. The arguments object serves as a way to alias the formal parameters of a function. Setting the value of arguments[0] also sets the value of the first declared parameter to the function.

Upvotes: 5

Related Questions