简体   繁体   English

JavaScript 正常 function 与箭头 function - 如何设置新的 Z31A1FD140BE4BEF2D18E5EC8DA21

[英]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 .我在我的方法中需要一个新的 scope ,但是在回调中运行某些内容后,我想将 scope 绑定回全局 object ,就像在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.我希望我的意思很清楚,我必须在回调中访问两个范围,实际上是 vue 实例中的data object 。 Is something like that possible?这样的事情可能吗?

try this尝试这个

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

simple function for normal usage arrow function for OOP usage简单 function 用于正常使用 箭头 function 用于 OOP 使用

the better way by making constructor and then make objects from this constructor更好的方法是创建构造函数,然后从这个构造函数中创建对象

for ex:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM