Class method cannot access properties

I created a class like this:

function MyClass() { var myInt = 1; } MyClass.prototype.EventHandler = function(e) { alert(this.myInt); } 

Unfortunately, this is a triggered event (in my cache tag), and I cannot access the properties of the class.

Any suggestions?

+4
source share
4 answers

It depends on how you pass the event handler when registering the event.

Following code

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

will not do what you want.

Javascript does not handle delegates, such as C #, so myObject.EventHandler is not an EventHandler method called for myObject.

If you want to call an object method as an event handler, it is best to include it in a function.

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

"vars" declared in the constructor function will not be available for other public functions, they are considered "private members".

You can use this.myInt = 1 to make it public and accessible for all class methods:

 function MyClass(){ this.myInt = 1; // Public member } MyClass.prototype.EventHandler = function(e){ alert(this.myInt); } 

or you can have a "privileged" method to access the "private" member in the constructor area:

 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)

+4
source

JavaScript actually has no classes. MyClass is a constructor for an object whose prototype is the MyClass.prototype object.

The this may be misleading; its value in the function depends on which object calls the function as a property.

If you want to be able to call an object method from an event handler, you must use function closure, as Vincent Robert suggests.

I suggest you familiarize yourself with these links for more information on this :

Besides,

 function MyClass() { var myInt = 1; } 

This constructor sets a local variable inside a function that is not accessible from outside the function. If you want to initialize an object property, you need to use this.myInt = 1 . This value will be set only for objects constructed using new MyClass() , but not for the object of the MyClass function itself.

+2
source

Assuming you replace var myInt with this.myInt , you can refer to it as MyClass.myInt from MyClass.prototype.EventHandler without worrying about what this means.

0
source

All Articles