【问题标题】:JavasScript inheritance for constructors that return a function返回函数的构造函数的 Javascript 继承
【发布时间】:2011-04-12 08:03:19
【问题描述】:

在 JavaScript 中有没有办法从返回函数的构造函数继承?例如:

var A = function() {
  return function(input) {
    // do stuff
  };
};

var B = function() {};
B.prototype = new A();
var b = new B();

谢谢

【问题讨论】:

    标签: javascript inheritance prototype


    【解决方案1】:

    通过从构造函数返回一个函数,您并没有创建A 的实例,而是创建了函数的实例。因此,继承将不起作用。

    var A = function() { return function(input) {}; };
    var a = new A();
    >>> typeof a;
    "function"
    
    var A = function() {};
    var a = new A();
    >>> typeof a;
    "object"
    

    如果你需要BA继承返回的函数,你应该将它设置为A的方法,无论是在本地还是在原型链中,并以这种方式传递。

    var A = function() {
      this.method = function(input) {}
    };
    
    var B = function() {}
    B.prototype = new A();
    var b = new B();
    >>> b.method
    'function(input) { }'
    

    【讨论】:

    • 谢谢。我最终使用组合而不是继承来减少重复 - 我会向任何以这种工厂式方式使用构造函数的人推荐它。
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2023-03-06
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多