Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: assigning functions as callbacks and variable scope

Tags:

javascript

So, here's the deal. I'm using an onclick event to fire a function so with each click you will toggle between the divs original innerHTML and another variable. It works when I assign testfunction as a callback. Here's the code:

var c = '';

function testfunction()
{
    var a = this.innerHTML;

    var b = 'blah';

    if (a !== b)
    {
        c = a;
        return this.innerHTML = b;
    }
    else
    {
        return this.innerHTML = c;
    }

    window.onload = function()
    {
         document.getElementById('rightcontent').onclick = testfunction;
    }

I understand that the c retains it's value because of it's global scope. But what I don't understand is why c comes back undefined when I put the function into an anonymous callback as such:

    windows.onload = function()
    {
    document.getElementById('rightcontent').onclick = function()
    {
         this.innerHTML = testfunction();
    }
    }

There isn't a point to any of this, I'm just messing around...but I would like to know what's happening under the hood.

Sorry if this is covered elsewhere, I have looking through some posts to find my answer, but I can't find it.

Thanks in advance :-)

like image 212
whosmav Avatar asked Apr 24 '26 23:04

whosmav


1 Answers

I understand that the c retains it's value because of it's global scope. But what I don't understand is why c comes back undefined when I put the function into an anonymous callback as such:

In your second snippet, this is not equal to #rightcontent, it's equal to window. window.innerHTML is undefined so the first branch is taken in your if/else block.

c gets assigned undefined, and undefined is returned.

You can call a method and specify a particular context with call or apply:

document.getElementById('rightcontent').onclick = function () {
    this.innerHTML = testfunction.call(this);
}

Example: http://jsfiddle.net/dySA5/

The reason your first snippet doesn't exhibit this behavior is because the browser is setting this to be the clicked element when the method is called.

like image 181
Andrew Whitaker Avatar answered Apr 26 '26 12:04

Andrew Whitaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!