我注意到,似乎没有明确解释this关键字是什么以及如何在Stack Overflow站点上的JavaScript中正确(和错误地)使用它.
我亲眼目睹了一些非常奇怪的行为,并且无法理解为什么会发生这种行为.
this工作如何以及何时使用?
从我理解的文档中,.proxy()它将改变作为参数传递的函数的范围.请问有人能更好地向我解释一下吗?我们为什么要这样做?
在2009年,ECMAScript 5添加了一个内置bind()函数,它将一个对象作为参数并返回一个相同的函数,其中this将始终引用您传递它的对象.(我找不到任何看起来像规范文档链接的东西.)
这与jQuery的$.proxy()功能有何不同?难道$.proxy()是第一位的ECMAScript 5发布之前?是否有特别的原因,有利于$.proxy(function(){}, this)过function(){}.bind(this)?
So I have some javascript class and in one method I use jQuery to bind function to click event. And within this function I need to call other methods of this class. In usual js function I did it through "this.method_name()", but here, I guess, jQuery redefines "this" pointer.
我最近正在研究小型聊天模块,它需要不断检查服务器是否有新消息.
我正在向服务器发送ajax请求,服务器保持连接,直到找到新消息(长轮询).
代码:
var chatController = function(){
//other variable declaration
/**
* Ajax call to monitor the new message , on complete of ajax call sending other call
*/
this.checkNewMessage = function(){
console.log(this); // placed this for debugging purpose
$.ajax({
url : SITEURL.CHECK_MESSAGE,
data : this.currrentUserDetails,
dataType : 'json' ,
cache : false,
success :(function(obj){
//temp = obj;
return obj.parseNewMessageResponse;
})(this),
complete: (function(obj){
//temp = obj;
return obj.checkNewMessage;
})(this),
});
};
// other function and variable
});
Run Code Online (Sandbox Code Playgroud)
当我试着打电话的时候
var mainController …Run Code Online (Sandbox Code Playgroud)