Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method can't access properties

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?

like image 957
Amir Avatar asked Dec 31 '22 02:12

Amir


1 Answers

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

like image 139
Christian C. Salvadó Avatar answered Jan 08 '23 14:01

Christian C. Salvadó