2011-05-07 99 views

回答

1

嗯。不,我不这么认为。 this不可设置。你不能改变它,尽管你可以给它添加属性。您可以make calls that cause this to be set,但不能直接设置它。

你可以做这样的事情:

function AjaxRequest (parameters) { 
    this.xhr = null; 
    if (window.XMLHttpRequest) { 
     this.xhr = new XMLHttpRequest(); 
    } 
    else if (typeof ActiveXOBject != 'undefined') { 
     this.xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
} 

AjaxRequest.prototype.someMethod = function (url) { 
    this.xhr.open('Get', url, true); 
    this.req.onreadystatechange = function(event) { 
     ... 
    }; 
    this.xhr.send(...); 
}; 

退一步,我觉得你的设计也不是很清楚。你想要做什么?另一种方法是您为拍摄的使用模式是什么?你想从AjaxRequest中揭示什么动词有什么方法?

如果你看看jQuery,他们的“ajax请求”不是一个对象,它是一种方法。 $ajax()....

什么是您的的想法?

这将决定您如何使用xhr属性,等等。

+0

非常感谢!我试图看看我是否可以将Ajax请求作为对象。我是JavaScript新手,并认为将每个请求视为对象是有意义的。但显然我应该去做功能。非常感谢! – Mansiemans 2011-05-07 11:52:05

+0

实际上,至少有一些有限的工具可以使用'apply()'和'call()'在JavaScript中设置'this'的值。请参阅:http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx – aroth 2011-05-07 11:53:20

+0

@aroth,这是在答案中指出的。 – Cheeso 2011-05-07 11:57:16

6

可以从构造函数中返回不同类型的对象,但不完全像你想要做的那样。如果您返回一个对象,而不是undefined(这是默认返回值),则它会将其替换为new表达式的结果。该对象不会从构造函数中获取它的原型(并且x instanceof AjaxRequest将不起作用)。

这将让你接近,如果这就是你要如何做到这一点:

function AjaxRequest (parameters) { 
    var result; 

    if (window.XMLHttpRequest) 
     result = new XMLHttpRequest(); 
    else if (typeof ActiveXOBject != 'undefined') 
     result = new ActiveXObject("Microsoft.XMLHTTP"); 

    // result is not an AjaxRequest object, so you'll have to add properties here 
    result.someMethod = function() { ... }; 

    // Use result as the "new" object instead of this 
    return result; 
} 
+0

您会考虑哪种解决方案'更清洁',你的还是Cheeso提出的方法,其中'object-to-differ'作为AjaxRequest对象的字段存储? – Mansiemans 2011-05-09 13:22:56

+1

虽然从“构造函数”返回不同的类型,可能会令人困惑,因为您希望能够将方法添加到'AjaxRequest.prototype'并使用'instanceof'。Cheeso解决方案的缺点是必须编写包装器才能将所有函数调用转发到真正的XHR对象或者直接访问它('like myObject.xhr.send()')。 – 2011-05-09 15:32:31

+1

Cheeso解决方案的另一个(可能的)好处是你可以定义你自己的更简单的接口,比如jQuery,Prototype,Dojo等。 – 2011-05-09 15:34:56

相关问题