0

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?

4
  • 2
    Call it like window.onload = function() { devark.init(); };. Learn how the this keyword works. Commented Sep 12, 2013 at 13:03
  • 1
    Works here: jsfiddle.net/kADvm Commented Sep 12, 2013 at 13:03
  • @Bergi You rock !!!!! but what was the error for? What is the diff? Commented Sep 12, 2013 at 13:06
  • @tymeJV bcoz JSFiddle has called the object's method exactly as Bergi said. View the source. Commented Sep 12, 2013 at 13:07

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@MuhammadTalhaAkbar, I added an alternative way of achieving the same thing.
Yeah I have seen it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.