如何克隆 ES6 class 对象构造函数?
How to clone an ES6 class object constructor?
使用 ES6 classes 制作一个简单的 ORM,我 运行 遇到阻塞问题 – 我无法正确复制 class(就像 [=13] =] 在 ES5 中)。
具体来说,这是我尝试过的:
class BaseModel {
echo() {
console.log(this.props);
}
static _setProperties(props) {
this.props = props;
}
}
function makeModel(props) {
// Try to copy the Class object
const Model =
Object.assign(Object.create(Object.getPrototypeOf(BaseModel)), BaseModel);
// Copy my static methods – is there a better way to do this?
Object.getOwnPropertyNames(BaseModel).forEach((key) => {
if (!key.startsWith('_')) return;
Model[key] = BaseModel[key];
});
// Configure the new model
Model._setProperties(props);
return Model;
}
const GreeterModel = makeModel('hello');
const greeter = new GreeterModel();
greeter.echo(); // Should log hello
我得到的错误是:
TypeError: GreeterModel is not a constructor
有什么方法可以用 ES6 classes 实现这个,还是我必须坚持使用 ES5 风格?
可选问题:有没有更好的方法来复制静态方法? getOwnPropertyNames
的解决方案并不理想,因为它 returns 也是只读属性,例如 length
.
谢谢!
你的基地有逻辑错误class。 this
总是取决于函数的调用方式。通常在构造函数上调用静态函数,即 BaseModel._setProperties(...)
在这种情况下 this
指的是 BaseModel
。
然而,实例方法是在实例本身上调用的,因此 this
指的是实例而不是构造函数。
要使 BaseModel
正常工作,您必须使用
echo() {
console.lof(this.constructor.props);
}
但要回答您的实际问题,您只需扩展 class:
function makeModel(props) {
class Model extends BaseModel {}
Model._setProperties(props);
return Model;
}
请注意,这不是 "cloning" 基础 class,而是对其进行扩展。没有合理的方法来克隆 JavaScript 中的函数(至少不是最重要的)。
使用 ES6 classes 制作一个简单的 ORM,我 运行 遇到阻塞问题 – 我无法正确复制 class(就像 [=13] =] 在 ES5 中)。
具体来说,这是我尝试过的:
class BaseModel {
echo() {
console.log(this.props);
}
static _setProperties(props) {
this.props = props;
}
}
function makeModel(props) {
// Try to copy the Class object
const Model =
Object.assign(Object.create(Object.getPrototypeOf(BaseModel)), BaseModel);
// Copy my static methods – is there a better way to do this?
Object.getOwnPropertyNames(BaseModel).forEach((key) => {
if (!key.startsWith('_')) return;
Model[key] = BaseModel[key];
});
// Configure the new model
Model._setProperties(props);
return Model;
}
const GreeterModel = makeModel('hello');
const greeter = new GreeterModel();
greeter.echo(); // Should log hello
我得到的错误是:
TypeError: GreeterModel is not a constructor
有什么方法可以用 ES6 classes 实现这个,还是我必须坚持使用 ES5 风格?
可选问题:有没有更好的方法来复制静态方法? getOwnPropertyNames
的解决方案并不理想,因为它 returns 也是只读属性,例如 length
.
谢谢!
你的基地有逻辑错误class。 this
总是取决于函数的调用方式。通常在构造函数上调用静态函数,即 BaseModel._setProperties(...)
在这种情况下 this
指的是 BaseModel
。
然而,实例方法是在实例本身上调用的,因此 this
指的是实例而不是构造函数。
要使 BaseModel
正常工作,您必须使用
echo() {
console.lof(this.constructor.props);
}
但要回答您的实际问题,您只需扩展 class:
function makeModel(props) {
class Model extends BaseModel {}
Model._setProperties(props);
return Model;
}
请注意,这不是 "cloning" 基础 class,而是对其进行扩展。没有合理的方法来克隆 JavaScript 中的函数(至少不是最重要的)。