javascript - 有没有更好的方法从构造函数返回对象和构造函数?

标签 javascript object constructor return return-value

我正在尝试返回一个对象以及构造函数。我有一些东西可以工作,但它有点难看,希望有更好的方法。

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/

相关文章:

javascript - 关于 : Vue. js 操作/突变的澄清

javascript - Chrome Web 检查器一次切换所有调试器点。

javascript - Sequelize : error of foreignKey constraint not reported when inserting new data?

oop - OCaml 中对象内的对象

c# - 如何在 C# 中从客户端的服务器获取构造函数?

c++ - 为数组的每个元素调用构造函数

c++ - 为什么当它作为静态成员变量出现时没有调用c++构造函数?

javascript - 当一个项目从带 Angular 子对象传递时获取父 ID

javascript - 如何在javascript中全局访问附加到元素的对象

javascript - 在javascript中存储多个数据