Skip to main content
edited body
Source Link
Dmitri Pavlutin
  • 19.3k
  • 8
  • 41
  • 46

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] = 12 modifies first argument a = 12.

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] = 1 modifies first argument a = 1.

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.

Source Link
Dmitri Pavlutin
  • 19.3k
  • 8
  • 41
  • 46

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] = 1 modifies first argument a = 1.