是否可以从javascript函数对象继承?

时间:2012-02-24 19:20:07

标签: javascript function inheritance object invoke

是否可以在javascript中创建自己的函数实现?使用__invoke魔术方法让javascript对象像php对象?

  A = function(){};
  A.prototype = new Function();

  var a = new A();
  alert( a instanceof Function ); // true
  a(); // exception

无法回答我自己的问题......有一个答案:

对不起的人来说,但是我找到了很好的办法(在发布问题时我离答案几步之遥)。我不删除问题,希望有人会花更少的时间和我在一起。

  A = function()
  {
    var f = function() { alert( 'f called' ) };
    f.__proto__ = A.prototype;
    return f;
  };

  A.prototype = Function( );
  A.prototype.method = function() { alert( 'method called' ) };

  var a = new A();
  alert( a instanceof Function ); // true
  alert( a instanceof A ); // true
  a(); // f called
  a.method(); // method called 

如果是新手问题请给我发电子邮件,我会删除它。谢谢!

2 个答案:

答案 0 :(得分:0)

不是很好吗?不幸的是,没有好办法。

正如您可能已经注意到的那样,问题是将函数设置为构造函数的prototype然后使用new调用构造函数会导致一个普通的旧对象,而不是一个可调用的函数对象

根据您的需要,有一种可能的半解决方法。这是一个有趣的技巧,但可能不适合现实世界使用。您可以创建iframe并从iframe的窗口中抓取Function。现在你有Function的“副本”,你可以做任何你想做的事情,而不会弄乱你的“真正的”Function功能。

var frame = document.createElement('iframe');
frame.id = frame.name = 'hacks';
frame.style.zIndex = '-1';
document.appendChild(frame);
var MyFunction = frames['hacks'].Function;
// add stuff to MyFunction and MyFunction.prototype

答案 1 :(得分:0)

这个怎么样:

function MyFunction ( f ) {
    _.extend( f, MyFunction.prototype );
    return f;
};

MyFunction.prototype.method = function () {
    alert( 'method called' );
};

var func = MyFunction( function () {
    alert( 'function called' );
});

现场演示: http://jsfiddle.net/nZczW/

因此,您可以通过将自定义函数传递给自定义函数构造函数来创建自定义函数:

var func = MyFunction( function () {...} );

方法是在构造函数的原型上定义的(通常):

MyFunction.prototype.foo = function () {...};

在构造函数中,方法直接在函数本身上分配。 (我使用了underscore.js的_.extend())。因此,您的函数仍然直接从Function.prototype继承。

您当然可以简化此模式:

var methods = { /* hash of methods */ };

var func = _.extend( function () { ... }, methods );
相关问题