我喜欢在javascript中,我可以创建一个函数,然后向该函数添加更多的方法和属性
myInstance = function() {return 5}
myInstance.attr = 10
Run Code Online (Sandbox Code Playgroud)
我想创建一个类来生成这些对象.我假设我必须从Function基类继承.
换句话说,我想:
var myInstance = new myFunctionClass()
var x = myInstance()
// x == 5
Run Code Online (Sandbox Code Playgroud)
但我不知道如何创建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
Run Code Online (Sandbox Code Playgroud)
我还试过这里找到的更复杂(也更合适?)的继承方法:如何在JavaScript中"正确"创建自定义对象?,没有更多的运气.我也尝试使用node.js中的util.inherits(myFunctionClass,Function).仍然没有运气
我已经筋疲力尽了谷歌,因此我觉得我必须遗漏一些基本或明显的东西.非常感谢帮助.
javascript inheritance function-object prototypal-inheritance