SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with JS Object

    Hey, this is a very simplified version of a Dashboard script I'm writing. I'm new to using objects, so I'm missing something here. I'm trying to figure out why inside download.start() the object variable "this.size" calls the right number, but in download.done(), it's coming up as undefined. Any help?

    Code:
    var download = {
    	size : null,
    	
    	start : function(startSize) {
    		this.size = startSize;
    		setTimeout(this.done, 2000);
    		alert("The Size is: " + this.size);
    	},
    	
    	done : function() {
    		alert("Now, the Size is: " + this.size);
    	}
    }
    
    window.onload = function() {
    	download.start(10);
    }

    EDIT:

    Ok I figured it out...

    setTimeout("download.done();", 2000); instead of setTimeout(this.done, 2000);
    Last edited by funkdaddy; Dec 19, 2006 at 15:34.

  2. #2
    Awesome Addict
    Join Date
    Mar 2004
    Location
    Toronto, Canada
    Posts
    326
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    FYI if you're using the Prototype JavaScript library at all you can keep the reference to "this" as the download object using the bind() method:
    Code:
    	var download = {
    		size : null,
    
    		start : function(startSize) {
    			this.size = startSize;
    			setTimeout("this.done", 2000);
    			alert("The Size is: " + this.size);
    		}.bind(this),
    
    		done : function() {
    			alert("Now, the Size is: " + this.size);
    		}
    	}
    
    	window.onload = function() {
    		download.start(10);
    	}

  3. #3
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's better to pass a function as the first argument to the setTimeout. Passing a String means it has to do an eval on it. I would do the following instead
    Code:
    var download = {
    	size : null,
    	
    	start : function(startSize) {
    		var oThis = this;
    		this.size = startSize;
    		setTimeout(function() {
    			oThis.done();
    		}, 2000);
    		alert("The Size is: " + this.size);
    	},
    	
    	done : function() {
    		alert("Now, the Size is: " + this.size);
    	}
    }
    
    window.onload = function() {
    	download.start(10);
    }


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
  •