的“这”一个回调函数的值 [英] The value of 'this' in a callback function

查看:106
本文介绍了的“这”一个回调函数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code做一个Ajax请求到web服务:

I have this code for doing an ajax request to a webservice:

var MyCode = {
	req: new XMLHttpRequest(), // firefox only at the moment

	service_url: "http://url/to/Service.asmx",

	sayhello: function() {
		if (this.req.readyState == 4 || this.req.readyState == 0) {
			this.req.open("POST", this.service_url + '/HelloWorld', true);
			this.req.setRequestHeader('Content-Type','application/json; charset=utf-8');
			this.req.onreadystatechange = this.handleReceive; 
			var param = '{}';
			this.req.send(param);
		}
	},

	handleReceive: function() {
		if (this.req.readyState == 4) {
			// todo: using eval for json is dangerous
			var response = eval("(" + this.req.responseText + ")");
			alert(response);
		}
	}
}

这就是所谓的当然是有我的code.sayhello()。

It is called with MyCode.sayhello() of course.

与它的问题是,REQ没有定义在在handleReceive函数的第一行。它得到所谓的4倍,所以我知道code以上将请求发送到服务器。

The problem with it is that "req is not defined" at the first line in the handleReceive function. It does get called 4 times, so I know the code above sends the request to the server.

我该如何解决这个问题?

How can I solve this?

推荐答案

经典闭合问题。当你的回调,封实际上是指已经到HTTP对象。

Classic closure problem. When you get the callback, the closure actually refers already to the HTTP object.

您可以执行以下操作有人建议:

You can do the following as someone suggests:

var that = this;
this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); };

或只是做到以下几点:

OR just do the following:

var that = this;
this.req.onreadystatechange = function() { that.handleReceive(); };

这篇关于的“这”一个回调函数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆