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
  1. #1
    New Coder
    Join Date
    Apr 2006
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problem with 'this'

    Hi!

    Code:
    obj=new Object()
    obj.prop='hello'
    obj.func=function()
      {
      alert(this.prop)
      setTimeout(this.func,10)
      }
    obj.func()
    I think this should keep alerting 'hello' but for some reason it doesn't. Can you help me out with this?
    Thank you!

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    this comes from the object part of object.member(). If you move a function from object to anotherObject, and call anotherObject.member() then the value of this will be anotherObject.

    In this case, you're not calling the function yourself, however. setTimeout calls it for you. But you handed setTimeout the function object itself, which has no binding to the this object. So, the this object will be the global object instead, like all normal function calls. Is there a way to solve this? Of course.

    Code:
    var
        obj={
            prop:'hello',
            func:function(){
                var
                    me=this;
                alert(this.prop);
                setTimeout(function(){me.func()},10);
            }};
    obj.func();
    Last edited by liorean; 02-02-2007 at 03:04 PM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    New Coder
    Join Date
    Apr 2006
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I see it now!
    Thanks!


  •  

    Posting Permissions

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