SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Aug 2007
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    link to "this" in anonymous function ?

    please help...how to create a link to "this" in anoymous function?
    HTML Code:
    (function() {
        
        function OnClick()
        {
            console.log(that.id);
        }
        ClassA = function(id)
        {
             this.id = id;
             this.element = document.getElementById(id);
             this.element.onclick = OnClick;
             // secret link
             that = this;
        }
    })();
    
    for(var i...)
    {
          var x = new ClassA("element_" + id);
    }
    if i do so..."that" in each instance of ClassA is always the last instance. I understand why it doesn't work...but it just interesting..is it possible to create somehow this secret link or not?
    I have tryed so:

    HTML Code:
    that = function (t) {
            return t;
    }(this);
    and so...
    HTML Code:
    GetThis = function (t) {
         return function () { return t };
    }(this);
    nothing works...is it possible?

  2. #2
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not 100% sure I follow what you're trying to do. It looks like you want the OnClick function to have a reference to the classA containing the element that was clicked.

    Well, a reference to the clicked element will be passed to OnClick as 'this'. If each element has a link to its classA, you could then get the id you want.

    In classA: this.element.that = this;

    In OnClick: console.log(this.that.id);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •