【问题标题】:Javascript Objects and the this keywordJavascript 对象和 this 关键字
【发布时间】:2012-09-06 22:45:32
【问题描述】:

我知道 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 在这种情况下不起作用以及如何使其参考正确的对象。

感谢您的帮助。

【问题讨论】:

  • console.log(this) 在 Firefox 或 Chrome 中有助于确定 this 在代码的某个部分(范围)中所指的内容。此外,this 不是对象所有者,而是对象本身。另一个方便的技巧是使用typeof(this)this.constructor 获取有关对象的更多信息。
  • 我明白了。就是这样,this.OnSuccess 如果指向对象 xmlHttpRequest。有道理,看你说的。但是当我在 Class 块上尝试时,类似: var self = this;然后我不能覆盖类方法,因为它总是引用主类。这有意义吗?
  • 我按照 Jfriend00 所说的做了:function Ajax_Class() { var self = this; (...) 然后在状态更改时尝试: self.OnSuccess();那么它总是会调用默认类的 OnSuccess 函数,而不是我在子类上设置的那个……
  • 很高兴你解决了这个问题。对于原型设计和范围解析,试试这个resource。 “对象属性名称的解析”部分。
  • @MalSu—this 与范围无关,它们是完全不同的东西。在 ES5 严格模式下,this 可以是任何东西,甚至是undefinednull。为引用 Richard Cornford 表示敬意。

标签: javascript class object this


【解决方案1】:

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),以便您可以从你的回调函数中引用它。

【讨论】:

  • 请注意,callapply,以及最近的bind,都可以将this 的上下文更改为您想要的任何内容,后者在不执行函数的情况下这样做。
  • @leemachin - 我添加了.bind() - 已经有.call().apply()
  • 感谢您的回答。但这实际上让我感到困惑。那么当我创建一个对象的新实例时,它的预期行为是什么?
  • @IgorDonin - 你的问题只有 1/3 需要回答的信息。如果您创建一个名为myObject 的新对象并使用myObject.print() 在该对象上调用一个方法,那么this 将在该特定调用的print() 方法内设置为myObject。如果您有一个不同的对象yourObject 并调用yourObject.print(),那么this 将在print 方法的特定执行中设置为yourObject。调用者决定this 的设置方式。
  • 我的问题是整个类和对象实例化。都在那里,伙计。 update_state 是一个使用 Ajax_Class 作为原型的类,并且有一个覆盖原型的 OnSuccess 方法。 run_update_state 创建一个 update_state 的实例,它获取一个 http 请求的响应并处理它。我想要的是运行 update_state 的方法 OnSuccess 而不是原型的方法。
【解决方案2】:

也许你正在尝试做类似的事情:

function Base() {}

Base.prototype.showName = function() {
  alert('Base method: ' + this.name);
}

function Foo(name, arg){

   this.name = name;

  // Extend this if arg is an object
  if (typeof arg == 'object') {
    for (var p in arg) {

      // This references the new instance if called with new keyword
      if (arg.hasOwnProperty(p)) {
        this[p] = arg[p];
      }
    }
  }
}

Foo.prototype = new Base();

// Re-assign constructor property (not very useful but some to do like this)
Foo.prototype.constructor = Foo; 

var inst0 = new Foo('foo 0');

// Override inherited method
var inst1 = new Foo(
             'foo 1',
             {showName: function(){alert('Instance method: ' + this.name);}}
            );

inst0.showName(); // Base method: foo 0
inst1.showName(); // Instance method: foo 1

但还有其他(更简单?更好?)方法可以做到这一点。让原型继承和 javascript 的动态特性为你工作,不要仅仅因为你更熟悉它们就试图让它模仿其他继承模式。

【讨论】:

  • 我花了一段时间才看到您的回答中的智慧。干杯,伙计。
【解决方案3】:

你试过了吗

run_update_states = new update_states();

注意括号。

【讨论】:

  • 谢谢你的回答,伙计。我测试了它,但不行。当您创建一个对象的实例并同时运行一个函数时,预期的结果是什么?对象 run_update_states 是否被创建?
  • 如果这对你的脚本来说不是问题,你可以将你需要的函数onSuccesss作为参数传递给AjaxClass,如果存在的话,将其添加到对象中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2013-06-16
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多