Reputation: 1216
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
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:
var
at the function scope;var
(closure gets created at the moment of function definition),In your case, the third case applies. show
can't access text
because it is defined in a totally unrelated scope.
Upvotes: 1
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