我的问题是,我已经有了一个巨大的代码文件,所以我尝试将其中的部分分离到不同的文件/类中,以便进行更好的概述。所有新分离的类都必须从主类Person (在这个示例中)获得或设置数据,那么我如何管理它呢?
这里是我问题的一个小例子。
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()
发布于 2018-03-06 15:43:30
不确定这是否是构建代码的好方法,但您可以将bind()
函数bind()
到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)
https://stackoverflow.com/questions/49134497
复制相似问题