在Javascript中,为什么“这个”是运算符不一致? [英] In Javascript, why is the "this" operator inconsistent?

查看:109
本文介绍了在Javascript中,为什么“这个”是运算符不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,this运算符可以在不同的场景下引用不同的东西。

In JavaScript, the "this" operator can refer to different things under different scenarios.

通常在JavaScript对象中的方法中,它引用当前对象。

Typically in a method within a JavaScript "object", it refers to the current object.

但是当用作回调函数,它成为对调用对象的引用。

But when used as a callback, it becomes a reference to the calling object.

我发现这会导致代码出现问题,因为如果你在JavaScript对象中使用一个方法作为一个回调函数,你无法判断this是指当前的对象还是this是否指的是调用对象。

I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.

有人可以澄清关于如何解决这个问题的用法和最佳实践?

Can someone clarify usage and best practices regarding how to get around this problem?

   function TestObject() {
            TestObject.prototype.firstMethod = function(){
                      this.callback();
                      YAHOO.util.Connect.asyncRequest(method, uri, callBack);

            }

            TestObject.prototype.callBack = function(o){
              // do something with "this"
              //when method is called directly, "this" resolves to the current object
              //when invoked by the asyncRequest callback, "this" is not the current object
              //what design patterns can make this consistent?
              this.secondMethod();
            }
            TestObject.prototype.secondMethod = function() {
             alert('test');
            }
        }


推荐答案

In JavaScript,始终引用调用正在执行的函数的对象。因此,如果该函数被用作事件处理程序,将引用触发该事件的节点。但是如果你有一个对象并在其上调用一个函数,如:

In JavaScript, this always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, this will refer to the node that fired the event. But if you have an object and call a function on it like:

myObject.myFunction();

然后 myFunction 将引用 myObject 。它有意义吗?

Then this inside myFunction will refer to myObject. Does it make sense?

要绕过它,你需要使用闭包。您可以按如下方式更改代码:

To get around it you need to use closures. You can change your code as follows:

function TestObject() {
    TestObject.prototype.firstMethod = function(){
        this.callback();
        YAHOO.util.Connect.asyncRequest(method, uri, callBack);
    }            

    var that = this;
    TestObject.prototype.callBack = function(o){
        that.secondMethod();
    }

    TestObject.prototype.secondMethod = function() {
         alert('test');
    }
}

这篇关于在Javascript中,为什么“这个”是运算符不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆