Les
Les

Reputation: 547

Newbie: Javascript constructor and scope-context issue

I'm confused as to what the problem is with context in a JS constructor. Within the ctor I have a function declared. Before the call to that function this is set to the context of the ctor. Inside the function the value of this is set to window. I don't understand why. In the HTML the ctor is called with 'new'.

function MyCtor() {
    var myFunc = function() {
         debugger; // #2
         // code for myFunc
     }

     debugger;  // #1
     myFunc();
     debugger;  // #3
}

At debugger #1, this is set to MyCtor. At #2 this is window. And at #3 it is back to MyCtor.

I'm sure I'm missing something basic here, but I've read a lot on scope and context; obviously not enough.

Upvotes: 0

Views: 296

Answers (1)

Katana314
Katana314

Reputation: 8610

The this object is one of the most annoyingly hard-to-understand concepts in Javascript. And that's quite a contest to win... First off, you have to understand that it will be specific to each function you call - the context in which you call myFunc won't set it how you want it. Here's one way you can do it:

function MyCtor() {
    this.myFunc = function() {
         debugger; // #2
         // code for myFunc
     }

     debugger;  // #1
     this.myFunc();
     debugger;  // #3
}

Generally, there are only a few situations in which you can rely upon a function's this to be a particular value. All of them to my knowledge:

objectToBeThis.aFunction = function() { ... } // declare this function as
// an object property at any time - 
objectToBeThis.aFunction();

Or, not used as often is:

aFunction.call(objectToBeThis, extraArgument1, extraArgument2);

When a named, but not "owned" function (ie, var functionName = function(), or function functionName()) is called, then it will have window as its this argument. This part I'm less sure of as a certainty, but I just wouldn't use this inside such a method.

As in the case of your code, there's also "new MyCtor" - in which a new object is created to be returned, and that object is set to this inside of the constructor method.

Upvotes: 2

Related Questions