【问题标题】:JavaScript normal function vs arrow function - how to set new scopeJavaScript 普通函数与箭头函数 - 如何设置新范围
【发布时间】:2020-07-27 03:15:22
【问题描述】:
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 对象。有这样的可能吗?

【问题讨论】:

  • 为什么不const obj = { test(){ console.log(this); } };?见method notation

标签: javascript data-binding this bind


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    正常使用的简单功能 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();
    

    【讨论】:

    • 感谢您的努力,但实际上与我的问题无关:/
    • 'contractor parent' 控制多个对象的最佳方式:)
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 2015-11-05
    • 2015-11-03
    • 2022-12-06
    • 2019-04-12
    • 2017-03-13
    • 2020-05-07
    相关资源
    最近更新 更多