0

I wonder is there any diffrence, in below codes:

function x(){
   var a = 1;
}

and:

function x(){
   this.a = 1;
}
josh
  • 5
  • 1

3 Answers3

1

The first creates a locally-scoped variable, which will not be retained after the function exits (unless by a closure created inside the function).

The second creates an expando property on the this object, possibly overwriting any previous value for that property.

Anomie
  • 92,546
  • 13
  • 126
  • 145
  • … and the `this` object depends on how the function is called. By default you will be doing `x()` which is the same as `window.x()` so `this` is `window`. If you were to do `new x()` then `this` would be the new instance of the x 'class'. – Quentin Mar 05 '11 at 19:55
  • And if you use `x.call(...)` or `x.apply(...)` you can have `this` be whatever object you want. You could also do something like `foo.x = x; foo.x();`. And passing `x` to functions like `Array.filter` will result in differing values for `this` too. – Anomie Mar 05 '11 at 20:03
0

scope of variable will be changed.. the var inside function will be exist only when that function will called

Reference

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
-1

The scope.

this.a will check for a window property a, and makes it global

function x(){
   this.a = 1;
}

is equal to

var instantance_a;
function x(){
   instantance_a = 1;
}

or rather a global property lik

window.a

naveen
  • 53,448
  • 46
  • 161
  • 251