2011-05-07 100 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

相關問題