0
var red = {a: 2};

red.fn = function(b){
    console.log("A: "+a ", B : "+b);
}

red.fn(20);

this gives error:

a is not defined

But i suspect a is already available as a global object to the function fn then why is it not accessible. Any explanation would be helpful.

Thank you
  • 107,507
  • 28
  • 191
  • 224
  • `this.a` will be accessible. As `this` inside `fn()` will refer to `red` object when called as `red.fn(20)`. The error clearly states that `a` is not defined, `red.a` is. – Tushar Jan 28 '17 at 13:21

3 Answers3

6

Because unlike some other languages, the this. qualifier is not optional in JavaScript (because it works fundamentally differently from most other languages that have this; more here). You need to write it explicitly:

red.fn = function(b){
    console.log("A: " + this.a + ", B : " + b);
// ---------------------^^^^^
}

(You were also missing + in there...)

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

Here you go

var red = {a: 2};

red.fn = function(b){
    console.log("A: "+this.a+ ", B : "+b);    //update this line
}

red.fn(20);

EDIT : for a to be accessible within fn as you first tried, it should have been declared as a global variable in the first place, such as var a = 2. It'd still be a valid way to access it as a global object variable, but then you should have gone for console.log("A: "+red.a+ ", B : "+b);

Now, this.a implies you're using the object's properties (edited after RobG's comment), where a is accessible.

Console-buche
  • 385
  • 1
  • 12
0

Here the variable a would be translated to window.a which is undefined.

So it takes the matter up to the scope of the variable a. Like already mentioned in the answers in the post, we could use the encapsulated variable by using this.a or we could also use red.a.

Including few examples to explore further:


window.a:

a = 5;

var red = {
  a: 2
};

red.fn = function(b) {
  console.log("A: " + a + ", B : " + b);
}

red.fn(20);

object.a or red.a:

a = 5;

var red = {
  a: 2
};

red.fn = function(b) {
  console.log("A: " + red.a + ", B : " + b);
}

red.fn(20);

How it should translate as posted with local function scope:

var red = function() {
  var a = 2;

  this.fn = function(b) {
    console.log("A: " + a + ", B : " + b);
  };
};

var redObj = new red();
redObj.fn(20);
L J
  • 4,431
  • 3
  • 19
  • 28