从对象的内联函数中访问它 [英] Accessing this from within an object's inline function

查看:92
本文介绍了从对象的内联函数中访问它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在对象方法中的javascript内联函数中引用this。

I'm having difficulty referencing "this" from within a javascript inline function, within an object method.

var testObject = {
    oThis : this,
    testVariable : "somestring",
    init : function(){

       console.log(this.testVariable); // outputs testVariable as expected

       this.testObject.submit(function(){

            var anotherThis = this;
            console.log(this.testVariable) // undefined
            console.log(oThis.testVariable) // undefined
            console.log(testObject.testVariable) // outputs testVariable 
            console.log(anotherThis.testVariable) // undefined

    }

}

我如何访问 this.testVariable 来自提交函数?
我也使用jQuery,如果这有所不同。

How do I access this.testVariable from within the submit function? I'm also using jQuery as well, if that makes a difference.

我想知道这是否是最好的方法 - 也许我应该作为一个单独的函数提交,然后引用内联,如:

I wonder if this is the best approach - and maybe I should have submit as a separate function, and then reference that inline, like:

 init : function(){

    this.testObject.submit = this.submitForm;

 },
 submitForm : function(){
     // do validation here
     console.log(this.testVariable) // outputs testvariable

     .
     .
     .

     return valid; 
 }

但这似乎也不起作用 - 我想我会就像现在将提交函数内联在我的 init 方法中一样。

But this didn't seem to work either - and I think I'd just like to keep the submit function inline within my init method for now.

推荐答案

一种常见的方法是将指定为本地变量。

A common way is to assign the this you want to a local variable.

init: function() {
   var _this = this;
   this.testObject.submit(function() {
        console.log(_this.testVariable); // outputs testVariable 
   });
}

这篇关于从对象的内联函数中访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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