我喜欢在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
我在多态可调用对象上看到了这篇文章,并试图让它工作,但似乎它们并不是真正的多态,或者至少它们不尊重原型链.
此代码打印undefined,而不是"hello there".
这种方法不适用于原型,还是我做错了什么?
var callableType = function (constructor) {
return function () {
var callableInstance = function () {
return callableInstance.callOverload.apply(callableInstance, arguments);
};
constructor.apply(callableInstance, arguments);
return callableInstance;
};
};
var X = callableType(function() {
this.callOverload = function(){console.log('called!')};
});
X.prototype.hello = "hello there";
var x_i = new X();
console.log(x_i.hello);
Run Code Online (Sandbox Code Playgroud)