Vignesh Sharma
Vignesh Sharma

Reputation: 31

why property 'a' is not accessible from 'fn'

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.

Upvotes: 0

Views: 83

Answers (3)

Console-buche
Console-buche

Reputation: 405

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.

Upvotes: 0

jl_
jl_

Reputation: 5539

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);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075189

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...)

Upvotes: 6

Related Questions