Amir
Amir

Reputation: 1259

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?

Upvotes: 5

Views: 8332

Answers (4)

eyelidlessness
eyelidlessness

Reputation: 63519

Assuming you replace var myInt with this.myInt, you can reference it as MyClass.myInt from within MyClass.prototype.EventHandler without worry about what this refers to.

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827218

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

Upvotes: 5

Miles
Miles

Reputation: 32458

JavaScript doesn't actually have classes. MyClass is the constructor for an object whose prototype is the object MyClass.prototype.

The this keyword can be confusing to understand; its value in a function depends on what object the function is called as a property of.

If you want to be able to call a method of an object from an event handler, you should use a function closure like Vincent Robert suggests.

I suggest you check out these links for more information about this:

Furthermore,

function MyClass()
{
    var myInt = 1;
}

This constructor sets a local variable within the function which is not accessible from outside of the function. If you want to initialize a property of the object, you need to use this.myInt = 1. This value will only be set on objects constructed by new MyClass(), however, and not on the MyClass function object itself.

Upvotes: 2

Vincent Robert
Vincent Robert

Reputation: 36120

It depends on how you are giving your event handler when registering the event.

The following code

element.addEventListener("click", myObject.EventHandler);

will not do what you want.

Javascript does not handle delegates like C# would for example, so myObject.EventHandler is not the EventHandler method called for myObject.

If you want to call a method on an object as an event handler, the best is to wrap it into a function.

element.addEventListener("click", function(event)
{
    myObject.EventHandler(event);
});

Upvotes: 5

Related Questions