Class method can't access properties

2019-04-09 10:47发布

问题:

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 casss an tag), and i can't access the class properties.

Any suggestions?

回答1:

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);
});


回答2:

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



回答3:

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:

  • http://trephine.org/t/index.php?title=Understanding_JavaScript's_this_keyword
  • http://www.quirksmode.org/js/this.html

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.



回答4:

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.