I have created a class like so:
function MyClass()
{
var myInt = 1;
}
MyClass.prototype.EventHandler = function(e)
{
alert(this.myInt);
}
Unfortunately, the this
is the triggered event (in my case an <a>
tag), and I can't access the class properties.
Any suggestions?
"vars" declared in the constructor function will not be available on other public functions, they are considered as "private members".
You could use this.myInt = 1
to make the member public, and available to all the class methods:
function MyClass(){
this.myInt = 1; // Public member
}
MyClass.prototype.EventHandler = function(e){
alert(this.myInt);
}
or you could have a "privileged" method, to access the "private" member on the constructor scope:
function MyClass(){
var myInt = 1; // Private member
this.getMyInt = function(){ // Public getter
return myInt;
}
}
MyClass.prototype.EventHandler = function(e){
alert(this.getMyInt());
}
Recommended lecture: Private Members in JavaScript (Douglas Crockford)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With