Refactor Code

  • Gravatar
    How do you access the "this" value in JavaScript?

    by azamsharp on 7/5/2008 7:57:48 PM
  • Recently, while working on some JavaScript code I needed to access the object's property. The problem was that the access was done in a scope where "this" meant something else. So, here are couple of ways to perform this function. Which method do you use?
  • // using Prototype.js
    this.button.observe('click',this.selectRow.bindAsEventListener(this));

    // using the Apply method of JavaScript
    this.button.observe('click',createRef(this, function() { alert(this.num); }));

    // using MS AJAX library
    this.button.observe('click',Function.createDelegate(this,function() { alert(this.num); }));

    // holding the reference to the current object
    var self = this;

    // using the JQuery library
    $(this.button).bind('click',{self:this},function(event)
    {
    var that = event.data.self;
    alert(that.num);

    });

  • Refactor it!
Please log in to refactor the code! Login