javascript - 有没有更好的方法从构造函数返回对象和构造函数?
问题描述
我正在尝试与构造函数一起返回一个对象。我有一些工作,但它有点难看,希望有更好的方法。
function Something(val) {
if (!(this instanceof Something))
return new Something(val)
let Constructor = function() {
return function(val) {
return new Something(val)
}
}
let obj = new Constructor()
obj.test = val
return obj
}
let a = Something('a')
let b = new Something('b')
let c = b('c')
console.log(a) // { [Function] test: 'a' }
console.log(b) // { [Function] test: 'b' }
console.log(c) // { [Function] test: 'c' }
谢谢你的帮助。
编辑:
经过进一步考虑,我认为需要更多的解释,也决定从不同的角度来处理这个问题。
好的,让我看看我是否可以假设性地表达我的问题。我有一个 Factory 应该解析为另一个“类”(尽管使用 ES5 函数原型)。这个其他“类”应该能够具有可选的类构造函数以及我们所说的“类方法”。这个自定义类也需要是一个实例,以便它可以从它的方法中存储数据(参考this
)
理想情况下,我们需要以下语法。
const something = Something('customClass') // new keyword is optional
something.someMethod()
// or
something(optionalConfig).someMethod()
除了使用可选构造函数调用类之外,我们还必须实例化一个新实例。
这样这些行就作用于不同的实例:
something.someMethod() // refers to the instance already created
something(optionalConfig).someMethod() // new instance
something(otherOptionalConfig).someMethod() // new instance
解决方案
你似乎在寻找类似的东西
function Custom(config) {
function customInstance(moreConfig) {
return new Custom(config + moreConfig); // not calling Something!
}
Object.setPrototypeOf(customInstance, Custom.prototype);
customInstance.config = config;
customInstance.test = true
return customInstance;
}
Custom.prototype = Object.create(Function.prototype);
Custom.prototype.method = function() { … };
const constructors = {Custom, …};
function Something(className) {
if (!constructors.hasOwnProperty(className)) throw new Error("…");
return new constructors[className];
}
鉴于Custom
构造函数和Something
工厂无论如何都会返回一个(函数)对象,因此new
运算符无论如何都是可选的,您不需要显式检查它。
推荐阅读
- python - pycharm - 如何跟踪隐藏的类方法__get__
- c# - 使用 C# 删除 jpeg 图像的 EXIF 数据中除两个字段外的所有字段
- facebook-graph-api - Facebook 图形 API:入门
- postgresql - Postgresql查询构造
- r - DiD-approach:如何在生成的 pdata.frame 中删除重复的对(id-time)
- html - 仅在两次设置值时出现 TypeScript 调用签名错误
- java - java:有没有办法确定给定的字符串是否代表另一个操作系统上的绝对路径?
- flask - 生产模式下的 Flask 忽略 @app.errorhandler
- python - Docker 和 Python virtualenv 有什么区别?
- python - Python 和 MATLAB 中的警告类型