Skip to content Skip to sidebar Skip to footer

Javascript: Attaching Oop Methods To Events And The 'this' Keyword

I am new to OOP Javascript and am having trouble with the this keyword and events. What I'm trying to achieve is: I have multiple DOM objects and want to not only bind a common eve

Solution 1:

One thing I notice is that neither init nor scroll is a method on the instance.

So you only need to add init and not this.init to the load event:

addEvent(window,'load',init); // No "this." needed

And similarly:

addEvent(window,'scroll',scroll);

If you do decide to move them to the class (eg this.scroll and this.init etc), you can save a reference to this and refer to it in an anonymous function passed to addEvent:

var self = this;

this.init = function() {
    addEvent(window, 'scroll', function() {
        self.scroll()
    })
};

this.scroll = function() { /* ... */ };

addEvent(window,'load',function() {
    self.init()
});

This is called a closure.

Solution 2:

function MyConstructor() {
    this.foo = "bar";
    var me = this;
    function myClosure() {
        doSomethingWith(me.foo);
    }
}

Solution 3:

this is not determined until execution of the function. When attaching an event listener, you are passing a function, which does not carry scope with it. Therefore, on the specified event, the function is running in the scope of window, meaning that this will be equal to window. To force execution in a particular scope, you can use tricks like creating a new variable to equal this, such as:

var that = this;
...
addEvent(window,'scroll', function() {
    that.scroll()
});

Solution 4:

Add a method to the Function prototype that allows you to bind any function to any object:

Function.prototype.bind = function(object) {
   var __method = this;
   returnfunction() {
      return __method.apply(object, arguments);
   };
};

Declare your event handlers in the instance (keeps things tidy):

function ClassThatDoesSomething() {

  this.events = {
    init: ClassThatDoesSomething.init.bind(this),
    scroll: ClassThatDoesSomething.scroll.bind(this),
    etc: ClassThatDoesSomething.etc.bind(this)
  };
  ...
}

Now whenever you reference your events, they'll be automatically bound to the class instance. e.g.:

functioninit() {
  addEvent(window,'scroll',ClassThatDoesSomething.events.scroll);
}

Solution 5:

You can use closures for that:

functionClassThatDoesSomething() {
    var self=this;
    // ...functioninit() {
        addEvent(window,'scroll',self.scroll);
    }
}

Post a Comment for "Javascript: Attaching Oop Methods To Events And The 'this' Keyword"