www.webdeveloper.com
Results 1 to 3 of 3

Thread: Unexpected Scope

  1. #1
    Join Date
    Feb 2012
    Posts
    2

    Unexpected Scope

    Hello, I would call myself a fairly competent JavaScript programmer,
    but I ran into something expected today. Here's a snippet:
    NS.MyClass = function () {
    var initialize = function() {
    /* do something */
    NS.Instances[<uniqueId>] = this;
    }
    initialize();
    }

    var obj = new NS.MyClass();
    The object that ends up in NS.Instances[<uniqueId>] is DOMWindow, not
    the particular instance of that class. I can obviously fix it with
    call() but I've found a hole in my knowledge and am trying to
    understand. Could someone explain what is happening there?
    Thanks!
    R

  2. #2
    Join Date
    Jul 2003
    Location
    The City of Roses
    Posts
    2,503
    There are four ways to invoke a function that affects what "this" will be.

    • In function form -- f() -- "this" will be the global object.
    • In method form -- o.f() -- "this" will be the object "o".
    • In constructor form -- new f() -- "this" will be a new object that inherits from f.prototype.
    • And finally in apply/call form -- f.call(o) -- "this" will be the object "o".


    You're invoking "initialize" using the function form, which means "this" will always be the global object.
    for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"'))
    {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n";

  3. #3
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    The results you are getting are correct, as the initialize function you are calling is not part of the objects instance... so "this" will refer to the window object within that function.

    One of many ways to get around this is you could define a variable holding the instance, so you don't need to constantly pass it around:

    Code:
    NS.MyClass = function()
    { 
    	var that = this;
    	var initialize = function()
    	{ 
    		/* do something */ 
    		NS.Instances[<uniqueId>] = that; 
    	}; 
    	initialize(); 
    };
    
    var obj = new NS.MyClass();
    "that" can be anything you like, I also like using the word "self".

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles