Talha Akbar
Talha Akbar

Reputation: 10040

JS - called method is not a function

I have object:

var devark = {
    init: function() {
        var obj = this;
        obj.assignHandlers();
    },
    assignHandlers: function() {
        var obj = this;
        document.getElementById("menu-toggler").onclick = obj.documentFunctions[0];
    },
    documentFunctions: [
        function() {
            toggleClass(this, "opened");
        }
    ]
};

on window.load, I am calling the init method. That works fine but when it calls another object method assignHandlers, it throws an error:

[17:54:33.192] TypeError: obj.assignHandlers is not a function

Why is it?

Upvotes: 0

Views: 94

Answers (1)

plalx
plalx

Reputation: 43728

Like @Bergi said, it's a this value issue that can be solved by doing:

window.onload = function () {
    devark.init();
};

The difference between both ways is the value of this within the init function. To determine the natural value of this, look at the left-side of the . in a method call, such as obj.someFn();. Here the value of this within someFn will be obj. However, when you do window.onload = devark.init;, you can imagine the handler will later be invoke like window.onload(). Which means the value of this within the onload function, which is really the init function will be window, not devark.

You can also use Function.prototype.bind to bind a specific this value to a function.

window.onload = devark.init.bind(devark);

Upvotes: 2

Related Questions