如何正确使用Javascript“this”就我而言?

发布于 2024-12-01 08:55:30 字数 1667 浏览 1 评论 0原文

我有以下(简化的)代码:

var myModule = {

    submitDummyForm: function(){ 
        console.log(this); // the right object is logged out
        var that = this; // keep a reference
        $.ajax({
            type:'POST',
            url: 'http://localhost/',
            data: {dummyData: 'something'},
            dataType: 'json',
            success: that.dummyFormSuccess

        });
    },

    dummyFormSuccess: function(data){ 
        console.log(this); // 'this' is logged out as some foreign object, most probably jQuery.ajax object
    }
}

它会导致“this”在 dummyFormSuccess 中丢失,无论我使用 this.dummyFormSuccess 还是 that.dummyFormSuccessfor 作为我的 ajaxSubmitForm() 的参数。

但是下面的代码会根据我的需要执行:

var myModule = {

    submitDummyForm: function(){ 
        console.log(this); // the right object is logged out
        var that = this; // keep a reference
        $.ajax({
            type:'POST',
            url: 'http://localhost/',
            data: {dummyData: 'something'},
            dataType: 'json',
            success: function(data) {
                 that.dummyFormSuccess(data);
            }
        });
    },

    dummyFormSuccess: function(data){ 
       console.log(this); // now 'this' is logged out correctly as the real myModule object
    }
}

我仍然不太熟悉 Javascript 的高级主题,但我已经知道,“this”可能会被重新定义,具体取决于它的使用位置。我想如果我使用“that”来存储对“this”的引用,它也应该将我的“this”保留在被调用的函数中。看起来很奇怪,我可以在环绕函数中调用 that.dummyFormSuccess(data) 并且它在内部得到正确的“this”,但如果我只是将它分配给 $.ajax success,我的“this”就会丢失。

任何人都可以解释一下,“this”在我的案例中迷失在哪里以及为什么它在第二个示例中工作正常?这是 jQuery 的问题(也许 jQuery.ajax() 在我的例子中以某种方式覆盖了我的“this”)还是只是该语言的一个功能?

I have a following (simplified) code:

var myModule = {

    submitDummyForm: function(){ 
        console.log(this); // the right object is logged out
        var that = this; // keep a reference
        $.ajax({
            type:'POST',
            url: 'http://localhost/',
            data: {dummyData: 'something'},
            dataType: 'json',
            success: that.dummyFormSuccess

        });
    },

    dummyFormSuccess: function(data){ 
        console.log(this); // 'this' is logged out as some foreign object, most probably jQuery.ajax object
    }
}

It leads to 'this' being lost in the dummyFormSuccess, no matter if I use this.dummyFormSuccess or that.dummyFormSuccessfor as an argument for my ajaxSubmitForm().

But the following code gets executed as I need:

var myModule = {

    submitDummyForm: function(){ 
        console.log(this); // the right object is logged out
        var that = this; // keep a reference
        $.ajax({
            type:'POST',
            url: 'http://localhost/',
            data: {dummyData: 'something'},
            dataType: 'json',
            success: function(data) {
                 that.dummyFormSuccess(data);
            }
        });
    },

    dummyFormSuccess: function(data){ 
       console.log(this); // now 'this' is logged out correctly as the real myModule object
    }
}

I'm still not very comfortable with advanced topics of Javascript but I already know, that 'this' may get redefined, depending on where it is used. I thought if I use 'that' to store the reference to 'this', it should also keep my 'this' inside the called function. It seems weird, that I can call that.dummyFormSuccess(data) in a wrap-around function and it gets correct 'this' inside, but if I just assign it to $.ajax success, my 'this' gets lost.

Can anybody explain, where is 'this' getting lost in my case and why it works OK in the second example? Is it a problem with jQuery (maybe jQuery.ajax() overwrites my 'this' somehow in my case) or just a feature of the language?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

彩扇题诗 2024-12-08 08:55:30

一切都是正确的。您的 this 在第一个示例中丢失,因为您将分配函数 that.dummyFormSuccess 到 jQuery ajax 对象的 成功。因此,这样,在 jQuery 的深处,它被称为类似 ajax.success 的东西。因此,thisajax 对象覆盖。

使用第二种方法,您创建一个匿名函数并将其分配给 success。因此,在匿名函数中,this 指向 ajax 对象,但 that 变量是可访问的并且尚未被覆盖。

Everything is correct. Your this is lost in a first example because you are assigning function that.dummyFormSuccess to jQuery ajax object's success. So, this way, deep inside jQuery, it's called something like ajax.success. So, this is overwritten with ajax object.

With second approach you create an anonymous function and assgn it to success. So inside your anonymous function, this points to ajax object, but that variable is accessible and have not been overwritten.

老街孤人 2024-12-08 08:55:30

您误解了这个

this 参数的值由调用站点(调用您的函数的代码)决定。
当您传递 that.dummyFormSuccessthis.dummyFormSuccess 时,您只是传递一个恰好来自您的对象的函数。
thisthat 对象仅用于检索函数实例;它不与该功能捆绑在一起。

当 jQuery 调用您的回调时,它总是在 jqXHR 对象的上下文中调用它。
当您传递 function(data) { that.dummyFormSuccess(data); 时},您的函数表达式将在此 jqXHR 对象的上下文中调用。
但是,您的回调随后会在 that 的上下文中调用 dummyFormSuccess,因此它的 this 正是您想要的。

You're misunderstanding this.

The value of this parameter is determined by the callsite – the code that calls your function.
When you pass that.dummyFormSuccess or this.dummyFormSuccess, you're just passing a function that happens to come from your object.
The this or that object is just used to retrieve the function instance; it isn't bundled with the function.

When jQuery calls your callback, it always calls it in the context of the jqXHR object.
When you pass function(data) { that.dummyFormSuccess(data); }, your function expression is called in the context of this jqXHR object.
However, your callback then calls dummyFormSuccess in the context of that, so its this is what you want it to be.

蓝眸 2024-12-08 08:55:30

您可以将 JavaScript 中的“this”视为函数参数列表中的附加参数。
因此,函数的每次调用都会在 this 参数中包含自己的值。以下是 JS 中调用函数的三种方式

  • foo(); - 函数内部 this 将被设置为默认值
    命名空间对象(浏览器环境中的窗口)。

  • obj.foo(); - this 将在 foo() 中获取 obj 引用。

  • foo.call(obj); - 将调用“foo”,并将 this 设置为 obj(与上面相同)

You can treat 'this' in JavaScript as additional argument in function argument list.
So each call of function will contain its own value in this argument. Here are all three ways of invoking function in JS

  • foo(); - inside the function this will be set to default
    namespace object (window in case of browser environment).

  • obj.foo(); - this will get obj reference inside the foo().

  • foo.call(obj); - 'foo' will be called with this set to obj (same as above)

在梵高的星空下 2024-12-08 08:55:30

由于函数也可以表示对象(并且它是对象),因此 this 表示该函数。 (不同范围)

您需要做的是将 var that = this; 放在 dummyForm : function (上面的行)之外,然后执行 console.记录(那个)

var that = this;
dummyFormSuccess: function(data){ 
   console.log(that); // now 'this' is logged out correctly as the real myModule object
}

Since a function can also mean an object (and it is an object), this means that function. (different scopes)

What you need to do is put var that = this; outside of dummyForm : function (the line above it), and then do console.log(that).

var that = this;
dummyFormSuccess: function(data){ 
   console.log(that); // now 'this' is logged out correctly as the real myModule object
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文