代码之家  ›  专栏  ›  技术社区  ›  bonblow

ES6 |更改B类中A类的数据?[已关闭]

  •  0
  • bonblow  · 技术社区  · 8 年前

    我的问题是,我已经有一个巨大的代码文件,所以我尝试将它的一部分分离到不同的文件/类中,以便更好地进行概述。所有新的独立类都必须从名为Person的主类(在此exmaple中)获取或设置数据,那么我如何才能管理这些数据呢?

    这里有一个我的问题的小例子。

    class Person {
        constructor(name, age) {
            this._name = name
            this._age = age
        }
    
        entryPoint() {
            ClassTwo.someEditFunction()
        }
    }
    
    class ClassTwo {
        static someEditFunction() {
            // here I wanna edit this._name from Class Person (without returing(?))
        }
    }
    
    let person1 = new Person('John', 15)
    person1.entryPoint()
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Mark    8 年前

    不确定这是否真的是构建代码的好方法,但您可以 bind() 这个 ClassTwo 函数的实例 Person 得到你想要的。

    class ClassTwo {
      static someEditFunction() {
        // here I wanna edit this._name from Class Person (without returing(?))
        this._name = "changed"
      }
    }
    
    class Person {
      constructor(name, age) {
        this._name = name
        this._age = age
      }
    
      entryPoint() {
        // ClassTwo.someEditFunction.bind(this)()
        // call() is a better fit
        ClassTwo.someEditFunction.call(this)
    
      }
    }
    
    
    
    let person1 = new Person('John', 15)
    person1.entryPoint()
    console.log(person1)