Anubhav Gupta
Anubhav Gupta

Reputation: 1216

Using local variables with "apply" in Javascript

Why "show" method is not able to access "text" variable here ?

// @constructor A
var A = function(){

    //alerts some text variable
    this.show = function(){
       alert("Hello")
       alert(text);
  }

}

//@constructor B
var B = function(){

  //local text variable
  var text = "World";
  A.apply(this); // "show" method will get attached to B
}

var obj = new B();

//now calling show of B's object.
obj.show(); //returns error.



//Expected output
alerts "Hello"
alerts "World"

//Actual output
alerts "Hello" 
ReferenceError: text is not defined

Am I missing something here ? Shouldn't the "text" variable be accessible to B's "show" method?

Upvotes: 1

Views: 57

Answers (2)

Kos
Kos

Reputation: 72241

Unlike C++ or Java, Javascript doesn't have an implicit this.

If a function (like show) refers to this.foo, then only the value of this depends on how the function was called.

However, if show refers to a variable directly (like foo), then it can mean either:

  • a local variable, if it's defined using var at the function scope;
  • a variable from a closure, if the function is being defined inside another function that happens to define it with var (closure gets created at the moment of function definition),
  • a global variable otherwise.

In your case, the third case applies. show can't access text because it is defined in a totally unrelated scope.

Upvotes: 1

Suman Bogati
Suman Bogati

Reputation: 6349

You need to declare the text as property of B constructor this.text = "World"; something like this.

var A = function(){

    //alerts some text variable
    this.show = function(){
       alert("Hello")
       alert(this.text);
  }

}

//@constructor B
var B = function(){

  //local text variable
   this.text = "World";
  A.apply(this); // "show" method will get attached to B
}

var obj = new B();

//now calling show of B's object.
obj.show(); //returns error.

Upvotes: 0

Related Questions