Accessing this from within an object's inline function

北慕城南 提交于 2019-11-30 08:27:42

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 
   });
}

You could also do this using ES6 arrow functions:

init: function(){
    this.testObject.submit( () => {
        console.log(this.testVariable);
    }
}

Arrow functions capture the this value of the enclosing context, avoiding the need to assign this to a new variable, or to use bound functions.

The "this" variable is bound dynamically when a function — any function, regardless of where it was defined — is called.

Without seeing what that "submit" function is supposed to do, or where it's supposed to be used, it's hard to say how to change it. One thing you could do is to define "submit" in your "init" function:

init: function() {
  // whatever
  var instance = this;
  instance.submitForm = function() {
    console.log(instance.testVariable);
    // ...
  };
}

As long as "init" is called initially with "this" set to an instance of one of your objects, you should be good.

You can only access the oThis variable from the context of the object, which is lost because you are inside of another function. or through instantiating a new object. like this

var testInstance = new testObject();

Then you could access oThis by using:

testInstance.oThis;

but that would be redundant

I would try something like this Matt:

init: function(){

var self = this; // this allows you to access the parent object from different contexts

this.testObject.submit(function(){

    console.log(self.testVariable);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!