我喜欢在 javascript 中这样做,我可以创建一个函数,然后向该函数添加更多方法和属性
myInstance = function() {return 5}
myInstance.attr = 10
我想创建一个类来生成这些对象。我假设我必须从 Function 基类继承。
换句话说,我想:
var myInstance = new myFunctionClass()
var x = myInstance()
// x == 5
但我不知道如何创建 myFunctionClass。我尝试了以下方法,但它不起作用:
var myFunctionClass = function() {Function.call(this, "return 5")}
myFunctionClass.prototype = new Function()
myInstance = new myFunctionClass()
myInstance()
// I would hope this would return 5, but instead I get
// TypeError: Property 'myInstance' of object #<Object> is not a function
我还尝试了这里找到的更复杂(也更合适?)的继承方法:如何“正确”在 JavaScript 中创建自定义对象?,没有更多的运气。我还尝试使用 node.js 中的 util.inherits(myFunctionClass, Function)。仍然没有运气
我已经用尽了谷歌,因此觉得我一定遗漏了一些基本的或明显的东西。帮助将不胜感激。