我正在尝试返回一个对象以及构造函数。我有一些东西可以工作,但它有点难看,希望有更好的方法。
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' }
感谢您的帮助。
编辑:
经过进一步的考虑,我认为需要更多的解释,并决定从不同的 Angular 来解决这个问题。
好吧,让我看看我是否可以假设地阐明我的问题。我有一个应该解析为另一个“类”的工厂(尽管使用 ES5 函数原型(prototype))。这个另一个“类”应该能够有一个可选的类构造函数以及我们所说的“类方法”。此自定义类还需要是一个实例,以便它可以在其方法中存储数据(引用 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
运算符无论如何都是可选的,并且您不需要明确地检查它。
关于javascript - 有没有更好的方法从构造函数返回对象和构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54771243/