javascript - 如何创建 Javascript Function 类的子类?

标签 javascript inheritance function oop

我想创建一个可以像这样使用的 Javascript 类:

var f = new myFunction(arg1, arg2);
f.arg1; // -> whatever was passed as arg1 in the constructor
f();
f instanceof myFunction // -> true
typeof f // -> function

我可以将其视为普通对象,甚至将 native Function 对象添加到原型(prototype)链中,但我不能像函数一样调用它:

function myFunction(arg1, arg2) {
  this.arg1 = arg1;
  this.arg2 = arg2;
}
myFunction.prototype = Function
var f = new myFunction(arg1, arg2); // ok
f.arg1; // ok
f(); // TypeError: f is not a function, it is object.
f instanceof myFunction // -> true
typeof f // -> object

我可以让构造函数返回一个函数,但它不是 myFunction 的实例:

function myFunction(arg1, arg2) {
  var anonFunction = function() {
  };
  anonFunction.arg1 = arg1;
  anonFunction.arg2 = arg2;
  return anonFunction;
}
var f = new myFunction(arg1, arg2); // ok
f.arg1; // ok
f(); // ok
f instanceof myFunction // -> false
typeof f // -> function

有什么建议吗?我应该补充一点,我真的想避免使用new Function(),因为我讨厌字符串代码块。

最佳答案

首先,您可能应该考虑其他一些方法来执行此操作,因为它不太可能是可移植的。我将假设 Rhino 作为我的答案。

其次,我不知道 Javascript 中有什么方法可以在构造后分配函数体。主体始终在构造对象时指定:

// Normal function definitions
function doSomething() { return 3 };
var doSomethingElse = function() { return 6; };

// Creates an anonymous function with an empty body
var doSomethingWeird = new Function;

现在,每个对象上都有一个以 __proto__ 属性形式出现的非标准 Mozilla 扩展。这允许您更改任何对象的继承链。您可以将其应用于您的函数对象,以在构造后为其提供不同的原型(prototype):

// Let's define a simple prototype for our special set of functions:
var OddFunction = {
  foobar: 3
};

// Now we want a real function with this prototype as it's parent.
// Create a regular function first:
var doSomething = function() {
  return: 9;
};

// And then, change it's prototype
doSomething.__proto__ = OddFunction;

// It now has the 'foobar' attribute!
doSomething.foobar;  // => 3
// And is still callable too!
doSomething();  // => 9

// And some of the output from your example:
doSomething instanceof OddFunction;  // => true
typeof doSomething;  // => function

关于javascript - 如何创建 Javascript Function 类的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2148997/

相关文章:

c++ - Cin 并指向所选函数

javascript - 在 AngularJS 中对一组对象进行分组

javascript - 单击 JQuery 中的按钮打开 UI 对话框

C++ : get inherited type from abstract pointer vector

java - 对这些父类和子类的解释?

C++ 继承模板类和初始化列表

c - C中是否允许这种函数调用

javascript - 如何在 crm 2011 表单上放置按钮。

javascript - 有一个简单但有用的 jquery.JsPlumb 示例吗?

javascript - 打开从 Raphael 节点到灯箱的链接