Search code examples
javascriptdata-bindingthisbind

JavaScript normal function vs arrow function - how to set new scope


const obj1 = {
  test: function() {
    console.log(this);
  }
};

const obj2 = {
  test: () => {
    console.log(this);
  }
};

obj1.test();
obj2.test();

I need a new scope in my method, but after running something in the callback, I want to bind the scope back to the global object, like in obj2.

Something like:

const obj1 = {
  test: function() {
    const newvalue = this.y;
    scope = bind(scope)
    this.globaldata = newvalue
  }
};

I hope it is clear what I mean, I have to access both scopes in a callback, acutally the data object in a vue instance. Is something like that possible?


Solution

  • try this

    const obj1 = {
      self: this,
      test: function() {
        const contextOfObj1 = this;
        const contextOfVueComponentInstance = obj1.self
        obj1.self.globaldata = newvalue
      }
    };