0

Possible Duplicate:
Javascript: Object Literal reference in own key’s function instead of ‘this’

I have this simple code :

var myObj = {
    init: function ()
    {
        this.Name = "Royi";
        this.BindMe();
    }
    BindMe: function ()
    {
        $('myButton').on("click", this.Work);
    },
    Work: function ()
    {
        var self = this; <--------
    }
}

Running :

myObj.init();

This is a simple Object literal. The problem is on the Work Method. I want to make it know this ( myObj)

there are 2 ways of doing it :

option #1

In BindMe , When clicking , transfer the context via :

$('myButton').on("click",{self:this}, this.Work);

and in Work do :

var self = e.data.self... //need also to add e

option #2

write var self = myObj ;

Question

  • Is there any other way of doing it ?

  • which is the better/correct way ?

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

3

Don't add it as data to the event object. Instead, use .bind() or the jQuery-ish (crossbrowser) proxy to provide the correct thisArg to the function (see MDN's introduction to the this keyword):

$('myButton').on("click", $.proxy(this, "Work"));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

You could pass the context to the handler function as part of a closure:

$('myButton').on("click", (function(context) {
    return function() {
        context.Work
    };
})(this));

Needless to say, this is cross browser, since it relies on one of the core features of JS.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139