Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Using "this"?

  1. #1
    Regular Coder
    Join Date
    Oct 2008
    Posts
    255
    Thanks
    113
    Thanked 0 Times in 0 Posts

    Using "this"?

    How can you tell when you're able to use "this" to reference something? I've never been quite clear on that...
    Last edited by Joseph Witchard; 02-18-2010 at 07:58 AM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,596
    Thanks
    80
    Thanked 4,633 Times in 4,595 Posts
    this can only refer to the *OBJECT* that invoked the function wherein it is found.

    So it could be
    Code:
    <img onclick="doSomethingWith(this);" .../>
    
    or
    
    // constructor for a Widget
    function Widget(n)
    {
         var name = n;
        
         function zam( ) { alert( this.n; ) }
    }
    In both cases, there is an object (in the first one, an object in the DOM, but still an object) and a method that "belongs" to that object, and so "this" refers to whichever instance of the object the method is invoked on.

    In other words:
    Code:
        var w1 = new Widget("woof");
        var w2 = new Widget("warp");
        w1.zam(); // does alert("woof");
        w2.zam(); // does alert("warp");
    JS, with it's anonymous functions capabilities and oddball methods of constructing object, can make figuring out just which object "this" refers to a challenge at times, but honest, it *will* be the "current object" as JavaScript views the objects.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Joseph Witchard (02-18-2010)

  • #3
    Regular Coder
    Join Date
    Oct 2008
    Posts
    255
    Thanks
    113
    Thanked 0 Times in 0 Posts
    Okay, thanks

    **EDIT: Why exactly is the name variable needed in the Widget function? Since you're alerting this.n instead of this.name?
    Last edited by Joseph Witchard; 02-19-2010 at 04:32 AM.


  •  

    Posting Permissions

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