Javascript 对象和 this 关键字

标签 javascript class object this

我知道this引用了对象所有者。但我很难让一个类正常工作,同时试图确定 this 所引用的内容。

我猜最好只显示代码:

function Ajax_Class(params) {
// Public Properties
this.Response = null;

// Private Properties
var RequestObj = null;

// Prototype Methods
this.OnReset    = function() { };
this.OnOpenConn = function() { };
this.OnDataSent = function() { };
this.OnLoading  = function() { };
this.OnSuccess  = function() { alert("default onSuccess method."); };
this.OnFailure  = function() { alert("default onFailure method."); };

// Public Methods
this.Close = function() {   // Abort current Request
    if (RequestObj) {
        RequestObj.abort();
        RequestObj = null;
        return true;
    } else return false;
};

// Private Methods
var Instance = function() {     // To create instance of Http Request
    try { return new XMLHttpRequest(); }
    catch (error) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (error) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (error) {}

    // throw new Error("Could not create HTTP request object.");
    return false;
};

var ReadyStateHandler = function() {
    // Switch through possible results
    switch(RequestObj.readyState) {
        case 0:
            this.OnReset();
        break;

        case 1:
            this.OnOpenConn();
        break;

        case 2:
            this.OnDataSent();
        break;

        case 3:
            this.OnLoading();
        break;

        case 4:
            // Check Status
            if (RequestObj.status == 200)  {
                // Handle Response
                Response = HandleResponse();
                // Call On Success
                this.OnSuccess();
                // Hide Loading Div
                LoadingDiv(true);
            } else {
                this.OnFailure();
            }

        break;
    } // End Switch
};

var Open = function() {
    // In case it's XML, Override the Mime Type
    if ((params["ResponseType"] == "XML") && (RequestObj.overrideMimeType)) 
        RequestObj.overrideMimeType('text/xml');

    // 
    if ((params["User"]) && (params["Password"]))
        RequestObj.open(params["Method"], params["URL"],  params["Async"], params["User"], params["Password"]);
    else if (params["User"])
        RequestObj.open(params["Method"], params["URL"],  params["Async"], params["User"]);
    else
        RequestObj.open(params["Method"], params["URL"],  params["Async"]);

    // Set Request Header ?
    if (params["method"] == "POST") 
        //this.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        RequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

};

var Send = function() {
    if (params["Data"])     RequestObj.send(params["Data"]);
    else                    RequestObj.send(null);
};

var HandleResponse = function() {
    if (params["ResponseType"] == "JSON")
        return ParseJSON(RequestObj.responseText);
    else if (params["ResponseType"] == "XML")
        return RequestObj.responseXML;
    else 
        return RequestObj.responseText;
};

// Method ParseJSON
var ParseJSON = function(obj) {
    if (obj)
        return JSON.parse(obj);
}; // End ParseJSON

// Method LoadingDiv -> Either Shows or Hides the Loading Div
var LoadingDiv = function(hide) {
    // Hide the Modal Window
    if (hide) { document.getElementById("Async").style.display = "none"; return false; }

    // Show Modal Window
    document.getElementById("Async").style.display = "block";

    // Reset the Position of the Modal_Content to 0, x and y
    document.getElementById("Async_Container").style.left = "0px";
    document.getElementById("Async_Container").style.top = "0px";

    // Center the Modal Area, no matter what the content
    var Screen_Width, Screen_Height;
        // Get screen data
        if (typeof(window.innerWidth) == "number") { Screen_Width = window.innerWidth; Screen_Height = window.innerHeight; }            //Non-IE
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {         //IE 6+ in 'standards compliant mode'
            Screen_Width = document.documentElement.clientWidth;
            Screen_Height = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {                                        //IE 4 compatible
            Screen_Width = document.body.clientWidth;
            Screen_Height = document.body.clientHeight;
        }

        // Set Modal_Content Max Height to allow overflow
        document.getElementById("Async_Container").style.maxHeight = Screen_Height - 200 + "px";

        // Get Modal_Container data
        var El_Width = document.getElementById("Async_Container").offsetWidth;
        var El_Height = document.getElementById("Async_Container").offsetHeight;


    // Set the Position of the Modal_Content
    document.getElementById("Async_Container").style.left = ((Screen_Width/2) - (El_Width/2)) + "px";
    document.getElementById("Async_Container").style.top = ((Screen_Height/2) - (El_Height/2)) + "px";
};


// Constructor

// Check the Params
// Required Params
if (!params["URL"]) return false;
// Default Params
params["Method"]        = (!params["Method"]) ? "GET" : params["Method"];   // GET, POST, PUT, PROPFIND
params["Async"]         = (params["Async"] === false) ? false : true;
params["ResponseType"]  = (!params["ResponseType"]) ? "JSON" : params["ResponseType"];  // JSON, TXT, XML
params["Loading"]       = (params["Loading"] === false) ? false : true;
// Optional Params
// params["User"])
// params["Password"]

// Create Instance of Http Request Object
RequestObj = Instance();

// Handle Ajax according to Async
if (params["Async"]) {
    // Handle what should be done in case readyState changes
    if (params["Loading"]) LoadingDiv();
    // State Handler || Response is Handled within the code
    RequestObj.onreadystatechange = ReadyStateHandler;
    // Open & Send
    Open();
    Send();
} else {
    // Handle the Loading Div
    if (params["Loading"]) LoadingDiv();
    // Open & Send
    Open();
    Send();
    // Handle Response
    this.Response = HandleResponse();
    // No State Handler, Application has been waiting for modifications.
    //this.OnSuccess(Response);
    // Handle the Loading Div
    LoadingDiv(true);
}

// no problems?
return true;

} // End Ajax

然后,在页面内:

window.onload = function() {

update_states = function() {
    this.OnSuccess = function() {
        alert("overriden onSuccess Method");
    };
};
    update_states.prototype = new Ajax_Class({URL:"ajax/states.php?id=5&seed="+Math.random()});
    run_update_states = new update_states;      

} // Window Onload

我想要做的是有一个默认的 OnSuccess (等)方法,并且,如果有需要,我可以使用子类方法覆盖默认方法,但它仍然会在 HttpRequest 状态下自动调用改变。

如果有人能给我指出正确的方向,我将不胜感激,如果我能够理解为什么这个在这种情况下不起作用以及如何使其引用正确的对象。

感谢您的帮助。

最佳答案

this 根据调用方式设置。以下是它的不同设置方式:

  1. func() - 正常的函数调用。 this 设置为全局对象(浏览器中的window)。

  2. obj.method() - 方法调用。 this 设置为 obj

  3. func.call(obj, arg1, arg2, ...) - 使用 .call()this 设置为 obj

  4. func.apply(obj, args) - 使用.apply()this 设置为 obj

  5. func.bind(obj, arg1, arg2, ...) - 使用 .bind()。创建一个新函数,在调用时将 this 设置为 obj(在内部,它在实现中使用 .apply())。

需要注意的典型事项。

  • 调用常规函数,即使是在对象的方法中,也会导致 this 指针位于该函数内的window
  • 回调函数通常会收到与其嵌入的代码不同的 this 值。您可能必须将原始 this 值保存到局部变量中(按照惯例,通常称为 self),因此您可以从回调函数中引用它。

关于Javascript 对象和 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12309523/

相关文章:

list - 使用drools检查列表的对象是否具有某些值

javascript - 有什么方法可以使用户上传的 SVG 图像免受代码注入(inject)等的影响?

javascript - 使用javascript将图像调整为全屏?

java - Android 中如何获取源类文件的包名?

c++ - 我应该包含包含在另一个标题中的文件吗?

PHP 类以某种方式发生冲突

c++ - 如何检查对象是否已在 C++ 中初始化/创建?

javascript - 如何计算 SVG 中的 d 路径?

javascript - THREE.js 3d 球体上的 MouseEvent 未在正确的位置触发

javascript - 如何将方法附加到函数的方法