JavaScript 普通函数 vs 箭头函数 - 如何设置新作用域

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

我的方法中需要一个新的范围,但是在回调中 运行 之后,我想将范围绑定回全局对象,如 obj2.

类似于:

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

我希望我的意思很清楚,我必须在回调中访问两个范围,实际上是 vue 实例中的 data 对象。这样的事情可能吗?

正常使用的简单功能 OOP 使用的箭头函数

更好的方法是创建构造函数,然后从该构造函数创建对象

例如:

// constructor 
function obj(){
    // arrow function 'recommended'
    this.test1 = () =>{
        console.log(this);
    }
   // normal function
    this.test2 = function(){
        console.log(this);
    }
}
   

// new object from constructor
const obj1 = new obj();
const obj2 = new obj();

obj1.test1();
obj1.test2();

obj2.test1();
obj2.test2();

试试这个

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