Here是一个小背景。
所以我有我的父类。构造函数接收两个对象:第一个是创建父对象实例的类(使用继承父类的其他类)。 第二个对象只是一些参数
parent.js
class ParentClass {
constructor(nativeObject, params) {
this.nativeObject = nativeObject;
this.param1 = params.param1;
this.param2 = params.param2;
}
// some logic here
}
module.exports = { ParentClass };
child.js
class ChildClass extends ParentClass {
// some logic here
}
module.exports = { ChildClass };
我在其他类方法中使用子类来创建它。我可以有多个文件,如下所示:
usingclasses.js
let { ChildClass } = require('path/to/my/child/class');
let opts = {
param1: 'idkSomeString';
param2: 42;
}
class MyCoolClass {
createChild() {
return new ChildClass(this, opts);
}
}
module.exports = { MyCoolClass };
anotherclasses.js
let { ChildClass } = require('path/to/my/child/class');
let opts = {
param1: 'thatAstringToo';
param2: 123;
}
class AnotherCoolClass{
alsoCreatesChild() {
return new ChildClass(this, opts);
}
}
module.exports = { AnotherCoolClass};
我可以在一个类中以不同的方法创建 ChildClass
的多个实例:
thirdexample.js
let { ChildClass } = require('path/to/my/child/class');
let opts1 = {
param1: 'aStringAgain';
param2: 27;
}
let opts2 = {
param1: 'ABC';
param2: 33;
}
class ClassAgain{
firstMethod() {
return new ChildClass(this, opts1);
}
secondMethod() {
return new ChildClass(this, opts2);
}
}
module.exports = { ClassAgain };
我传递.this
的原因是因为我在ParentClass
中使用它
例如用于记录 console.log(`我知道这是在 ${this.nativeObject .constructor.name}` 中创建的);
我正在寻找的是每次创建 ChildClass
的新实例时摆脱传递 .this
的方法
这背后的原因是,在一个文件(类)中,我最多可以创建 10 多个 ChildClass
实例。
在上一个问题中我已经得到了答案,它帮助我使代码更加结构化并且更易于维护:
而不是:
createChild() {
return new ChildClass(this, param1, param2, param3, paramN);
}
我正在做:
createChild() {
return new ChildClass(this, paramObj);
}
现在我可以将所有带有参数的对象存储在文件(甚至是单独的文件)顶部,并在需要时轻松查找和更改它。
...
现在我试图找到一种方法来摆脱 .this
每次创建 ChildClass
还有其他方法可以让 ParentClass
知道这个 ChildClass
实例“生活”在哪里吗?
我试图弄清楚我可以使用 .apply
或 .call
做一些事情,但似乎这不是我正在寻找的机器人
更新: 由于我在这方面的进展为零,而且我什至收到一条评论,说这很可能是不可能的,现在让我们假设我需要一个仅用于日志记录的创建 ChildClass 实例的类的名称。
如何在每次创建 ChildClass
时检索类的名称而不传递它?
let opts = {
className: 'MyCoolClass'
param1: 'idkSomeString';
param2: 42;
}
class MyCoolClass {
createChild() {
return new ChildClass(opts);
}
}
module.exports = { MyCoolClass };
问题是我必须一次又一次地在每个版本的 opts
中设置 className: 'MyCoolClass'
...只需重复 10 次即可-15次
最佳答案
您可以使用 Reflect.construct 实例化您的类.
class ParentClass {
constructor (nat, x) {
this.nat = nat
this.x = x
}
log () {
console.log('from ', this.nat.constructor.name, this.x)
}
}
class ChildClass extends ParentClass{}
class ClassAgain{
firstMethod () {
return this.makeInstance({ a: 1 })
}
secondMethod () {
return this.makeInstance({ b: 2 })
}
makeInstance (params) {
return Reflect.construct(ChildClass, [this, params])
}
}
const ca = new ClassAgain()
ca.firstMethod().log()
ca.secondMethod().log()
关于javascript - 一种无需传递 `.this` 作为参数即可检索上下文的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387568/