在Node.js中,Typescript和"@botstan/Magic"库存在一些问题。
在开始之前,请阅读“魔术” documentation。
遵循以下行:
import Magic from "@botstan/magic";
import * as _ from "lodash";
@Magic
export default class Base {
[key: string]: any;
props = {};
constructor (config = {}) {
const self = this;
_.forEach(config, (value, key) => {
self.__set(key, value);
});
}
__isset (name: string): boolean {
name = _.snakeCase(name);
return _.has(this.props, name);
}
__unset (name: string): void {
name = _.snakeCase(name);
_.unset(this.props, name);
}
__set (name: string, value: any): void {
name = _.snakeCase(name);
if (value !== null || value !== undefined) {
_.set(this.props, name, value);
return;
}
_.unset(this.props, name);
}
__get (name: string): any {
name = _.snakeCase(name);
return _.get(this.props, name, undefined);
}
}
如果您已经看过“ Magic” documentation,那么您知道我们刚刚在Typescript中创建了Magic类。
import Base from "./Base";
const obj = new Base();
obj.first_name = "Jone";
obj.last_name = "Done";
console.log(obj.first_name); // Jone
console.log(obj); // { props: { first_name: "Jone", last_name: "Done" } }
“基础”类运行良好,但是当我从该类扩展后,我们的问题开始了。
import Base from "./Base";
export default class Example extends Base {
someVar: any = false;
someMethod () {
}
}
现在,让我测试Example类。
import Example from "./Example";
const obj = new Example();
obj.first_name = "Jone";
obj.last_name = "Done";
console.log(obj.first_name); // Jone
console.log(obj); // { props: { }, first_name: "Jone", last_name: "Done" }
“ Example”类的工作方式不同于“ Base”类。我该怎么做才能解决这个问题?
答案 0 :(得分:0)
我读了“魔术”……个人看来,这是一个非常毫无价值的图书馆。就我个人而言,我不会触摸它并以此污染我的代码库。
此外,如果扩展一个类(使用通用的OO术语继承),并且该基类具有构造函数,则需要在派生类中调用super()
(在您的情况下为Example
) ,您不是。它也必须是在构造函数中进行的第一个调用,以正确初始化基类。试试看,看看是否可行:
export default class Example extends Base {
someVar: any = false;
constructor(){
super({}); // <-- empty obj because base class takes a single init param
}
someMethod () {
}
}