-1

I want my code give me "2" as a output but this shows me "1" as an output. Please tell me what changes must I do in my code so that it give me a correct result.

var a = 1;

function x() {
  var a = 2;

  function b() {
    var self = this;
    console.log(self.a);
  }

  b();
}

x();
deceze
  • 471,072
  • 76
  • 664
  • 811
Pulkit Aggarwal
  • 1,779
  • 3
  • 17
  • 27

3 Answers3

5

Global variables are properties of the window object, so self.a gives you 1 because self is window. (Further reading: How does the “this” keyword work?).

Local variables are not properties of any object. They can't be accessed as if they were properties of an object. Just log a and not self.a.

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
0

Try the following code which prints "2" to the browser console. Here I changed the function x to an object. Inside this I added "a" as a property and "b" as a function. Then finally call the b() function as "x.b()".

var a = 1;

var x=
{
    a :2,

    b: function()
    {
        var self = this;
        console.log(self.a);
    }


}

x.b();
Lahiru Tennakoon
  • 521
  • 1
  • 4
  • 6
-3

Try this out:

var a = 1;
function x() {
  a = 2;
  function b() {
    var self = this;
    console.log(self.a);
  }
  b();
}
x();
RRajani
  • 413
  • 3
  • 10
  • Thanks for suggetion, But i dont know why people down voting even code is having true logic. – RRajani Apr 03 '17 at 13:25
  • This reads more like a game of spot-the-difference than an answer. The question seems to be about how to read the correct variable, not about how to use only one variable. – Quentin Apr 03 '17 at 13:46