Results 1 to 3 of 3

Thread: Unexpected Scope

  1. #1
    Join Date
    Feb 2012

    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;

    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?

  2. #2
    Join Date
    Jul 2003
    The City of Roses
    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.

  3. #3
    Join Date
    Dec 2011
    Centurion, South Africa
    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:

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

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