相关疑难解决方法(0)

从对象的内联函数中访问它

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

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

    }

}
Run Code Online (Sandbox Code Playgroud)

如何this.testVariable从提交功能中进行访问?我也使用jQuery,如果这有所不同.

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

 init : function(){

    this.testObject.submit = this.submitForm;

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

     .
     .
     .

     return valid; 
 }
Run Code Online (Sandbox Code Playgroud)

但这似乎也没有用 - 我想我现在只想在我的init方法中保持提交函数内联.

javascript inline function object this

18
推荐指数
2
解决办法
2万
查看次数

没有黑客攻击,私有JavaScript函数无法访问'this'对象?

我正在研究一个项目一段时间,试图找出我做错了什么,当我最终将"错误"缩小到下面的代码不能按预期工作的事实时:

function Alpha()
    {
    this.onion = 'onion';

    function Beta()
        {
        alert(this.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'undefined'
Run Code Online (Sandbox Code Playgroud)

但是,如果我将代码更改为:

function Alpha()
    {
    var self = this;
    this.onion = 'onion';

    function Beta()
        {
        alert(self.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'onion'
Run Code Online (Sandbox Code Playgroud)

它像我期望的那样工作.在浪费了我生命中的大部分时间之后,任何人都可以解释为什么它会像这样工作吗?

javascript private this

7
推荐指数
2
解决办法
1312
查看次数

标签 统计

javascript ×2

this ×2

function ×1

inline ×1

object ×1

private ×1