jQuery/JavaScript “this” pointer confusion

自古美人都是妖i 提交于 2019-11-27 00:52:52
Aaron Qian

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:

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

Get the book: JavaScript: the Good Parts.

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

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
});

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);
}
this.bar();  // when called here, "this" is the foo instance

this comment is wrong when foo is used as a normal function, not as a constructor. here:

foo();//this stands for window
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!