Spencer Mark
Spencer Mark

Reputation: 5311

OOP JavaScript - this reference

For some strange reason, when calling a function that assigns this to thisObj, I get an error:

TypeError: thisObj is undefined

Here's what I've got:

function templateObject() 
{
    "use strict";
    var thisObj = this;

    function _loadBackgroundImages() 
    {
        "use strict";
        // something happens here
    }


    thisObj.initialise = function() 
    {
        "use strict";
        _loadBackgroundImages();
    };
}

The function is then called using the instantiation like so:

var templateObj = templateObject();
templateObj.initialise();

Can't figure out why I get the error - any idea?

Upvotes: -1

Views: 110

Answers (2)

Paul D. Waite
Paul D. Waite

Reputation: 98956

When you call a function like you've done (i.e. not as a method of an object):

templateObject()

Then, if you’re in strict mode, this will be undefined inside that function.

As @mishik pointed out, it looks like you wanted templateObject to be a constructor function, and to use it as such, you need to call it with the new keyword before it:

var templateObj = new templateObject();

One style note: it's conventional in JavaScript to name functions intended to be used as constructors with an initial capital.

That might make mistakes like this marginally less likely, as it'd look odd to see a function with an initial capital called without new:

function TemplateObject() {
    ...
}
var templateObj = new TemplateObject();

Upvotes: 0

mishik
mishik

Reputation: 10003

Use new:

var templateObj = new templateObject();

Calling function with new will pass newly created empty object as this to the function and then return it to templateObj.

Upvotes: 5

Related Questions