Skip to main content

jQuery/JavaScript "this” pointer confusion



The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?







// a class with a method



function foo() {



this.bar(); // when called here, "this" is the foo instance



var barf = this.bar;

barf(); // when called here, "this" is the global object



// when called from a click, "this" is the html element

$("#thing").after($("<div>click me</div>").click(barf));

}



foo.prototype.bar = function() {

alert(this);

}





Source: Tips4all

Comments

  1. Welcome to the world of javascript! :D

    You have wandered into the realm of javascript scope and closure.

    For the short answer:

    this.bar()


    is executed under the scope of foo, (as this refers to foo)

    var barf = this.bar;
    barf();


    is executed under the global scope.

    this.bar basically means:

    execute the function pointed by this.bar, under the scope of this (foo).
    When you copied this.bar to barf, and run barf. Javascript understood as, run the function pointed by barf, and since there is no this, it just runs in global scope.

    To correct this, you can change

    barf();


    to something like this:

    barf.apply(this);


    This tells Javascript to bind the scope of this to barf before executing it.

    For jquery events, you will need to use an anonymous function, or extend the bind function in prototype to support scoping.

    For more info:


    Good explanation on scoping
    Extending jQuery bind to supportscoping

    ReplyDelete
  2. There's a good explanation on this keyword in JavaScript available at QuirksMode.

    ReplyDelete
  3. You might find this:

    http://stackoverflow.com/questions/520019/controlling-the-value-of-this-in-a-jquery-event

    or this:

    http://www.learningjquery.com/2007/08/what-is-this

    Useful.

    ReplyDelete
  4. Get the book: JavaScript: the Good Parts.

    Also, read as much as you can by Douglas Crockford
    http://www.crockford.com/javascript/

    ReplyDelete
  5. You may use Function.apply on the function to set what this should refer to:

    $("#thing").after($("<div>click me</div>").click(function() {
    barf.apply(document); // now this refers to the document
    });

    ReplyDelete
  6. This is because this is always the instance that the function is attached to. In the case of an EventHandler it is the class that triggered the event.

    You can help your self with an anonymous function like this:

    function foo() {
    var obj = this;
    $("#thing").after($("<div>click me</div>").click(function(){obj.bar();}));
    }

    foo.prototype.bar = function() {
    alert(this);
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex