【发布时间】:2011-12-20 18:34:54
【问题描述】:
我喜欢在 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
我还尝试了这里找到的更复杂(也更合适?)的继承方法:How to "properly" create a custom object in JavaScript?,但没有更多的运气。我还尝试使用 node.js 中的 util.inherits(myFunctionClass, Function)。还是没有运气
我已经用尽了 Google,因此觉得我一定遗漏了一些基本的或明显的东西。非常感谢您的帮助。
【问题讨论】:
-
在 ECMAScript 第 3 版中无法执行此操作(使用
[[prototype]])。我不知道第 5 版中是否有一个棘手的方法允许这样做。 “常规”方法——例如在 jQuery 中使用 - 从“原型”复制各个属性,而不使用原型继承。
标签: javascript inheritance prototypal-inheritance function-object