我正在将一些javascript代码移植到typescript上,我遇到了一个问题。
我有一个ajax调用传递一个对象作为上下文,这个对象包含一些回调和一些其他信息,这些信息由成功或错误回调读出,指示成功调用应该重定向到哪里:
function SomeAjaxService
{
var self = this;
self.CheckErrorType = function(...) {
// Do something
};
var SuccessProxyCallback = function(results) {
// Do some stuff with results, like send off some events
this.successCallback(results);
};
var FailureProxyCallback = function(...) {
// Do some stuff with errors, and fire some events
var someErrorType = self.CheckErrorType(...);
this.failureCallback(someErrorType);
};
self.SendRequest = function(requestArgs) {
var ajaxSettings = {
context: requestArgs,
// Assign a load of stuff
};
$.ajax(ajaxSettings);
};
}
现在您可以看到,失败代理调用了一个本地方法,并使用了"this"上下文对象。那么如何用typescript处理这种情况呢?
您可以在构造函数中设置self = this
并像以前一样继续吗?
== EDIT ==
根据要求,这里是上面的一个类表示,显示了由于缺少self变量而导致的问题需要有2件事。
class SomeAjaxService
{
public CheckErrorType(someArg1: any, someArg2: any) {
// Do some stuff with data
};
private SuccessProxyCallback(results: any) {
// Do some stuff with results, like send off some events
this.successCallback(results);
// Does the above *THIS* usage point to the context of the
// Ajax call or the actual instantiated class
};
private FailureProxyCallback(...) {
// Do some stuff with errors, and fire some events
var someErrorType = this.CheckErrorType(...);
// The above *THIS* call cannot be correct if the context has overwritten
// the scope of this, however I dont know if this is true, do I even need
// this.CheckErrorType to invoke a local method?
this.failureCallback(someErrorType);
// As mentioned above same issue here but the *THIS* should hopefully
// point to the context object on the ajax object not the local instance.
};
public SendRequest(requestArgs: any) {
var ajaxSettings : JqueryAjaxSettings = {
context: requestArgs,
// Assign a load of stuff
};
$.ajax(ajaxSettings);
};
}
就像我上面说的,主要问题是,在一个方法中,我需要调用一个实例方法,以及从ajax调用调用上下文对象的方法。与原始的javascript,我将有self = this
,然后我可以得到周围的this
被覆盖,这是需要保持ajax异步状态对象的范围。
抽象地说,在构造函数中这样做通常不会解决任何问题(除非稍后在该方法中捕获它——见下文)。TypeScript类将类实例数据存储在对象本身,而不是捕获局部变量。因为你可以在构造函数中设置self = this,然后像以前一样继续吗?
self
将被存储在this
对象上,所以您最终不会拥有之前没有的任何东西。
有一种方法:
class SomeAjaxService
{
private FailureProxyCallback(context, arg) {
// now 'this' is the class instance and 'context' is requestArgs
}
public SendRequest(requestArgs) {
var self = this; // Note: captured local used in closure below
var ajaxSettings = {
context: requestArgs,
// Do not use an arrow function here, even though it's tempting!
error: function(arg) { self.FailureProxyCallback(this, arg) }
};
$.ajax(ajaxSettings);
};
}