jQuery/JavaScript “this” pointer confusion

前端 未结 7 722
余生分开走
余生分开走 2020-11-29 02:44

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 in

7条回答
  •  长情又很酷
    2020-11-29 02:50

    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

提交回复
热议问题