Javascript / Node.js:ES5子类实例访问父类方法

时间:2017-02-08 23:32:38

标签: javascript node.js

我正在尝试在子代的构造函数中访问父方法,如下所示:

file1.js

var ParentClass = function(arg) {
    this.arg = arg;
    this.result = {};
};

ParentClass.prototype = {
    constructor: ParentClass,
    isActive: function(condition) {
        return new Date(condition.valid).getTime() <= Date.now())
    }
};

module.exports = ParentClass;

file2.js

var ParentClass = require('file1');

var ChildClass= function(arg) {
    ParentClass.apply(this, arguments);
    this.init();
};

ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;

ChildClass.prototype = {
    init: function() {
        this.result = this.arg.validity
        .filter(function(elem) {
            return this.isActive(elem)
        }.bind(this));
    }
}

module.exports = ChildClass;

file3.js

var ChildClass= require('file2.js');
var instance = new ChildClass(param);

初始化这样的实例给了我

TypeError: this.isActive is not a function
  at Object.<anonymous> (file2.js)
  at Array.filter (native)
  at Object.ChildClass.init (file2.js)

帮助和解释表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:3)

您有两个单独的ChildClass.prototype作业。一个会覆盖另一个。相反,您需要首先使用Object.create()初始化原型,然后您需要为其添加新方法,而不是分配给整个原型,从而替换您刚刚放置的所有内容。

这是两个相互矛盾的陈述:

ChildClass.prototype = Object.create(ParentClass.prototype);

ChildClass.prototype = {...};

解决此问题的一种常见方法是使用Object.assign()将您的方法复制到现有原型中:

Object.assign(ChildClass.prototype, {
    init: function() {
        this.result = this.arg.validity
        .filter(function(elem) {
            return this.isActive(elem)
        }.bind(this));
    }
});

这会将您的每个方法复制到现有的原型对象中,当您有很多方法时,这种方法会更常用。

您也可以一次分配一个新方法(当您只有几个方法时更常用):

ChildClass.prototype.init = function() {
    this.result = this.arg.validity.filter(function(elem) {
        return this.isActive(elem)
    }.bind(this));
}

答案 1 :(得分:0)

您正在将ChildClass.prototype重新定义为一个新对象,它会先使用Object.create()覆盖您的作业。相反,只需在其上定义init方法即可。

试试这个:

&#13;
&#13;
var ParentClass = function(arg) {
  this.arg = arg;
  this.result = {};
};

ParentClass.prototype = {
  constructor: ParentClass,
  isActive: function(condition) {
    return new Date(condition.valid).getTime() <= Date.now();
  }
};

var ChildClass = function(arg) {
  ParentClass.apply(this, arguments);
  this.init();
};

ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;
ChildClass.prototype.init = function() {
  this.result = this.arg.validity
    .filter(function(elem) {
      return this.isActive(elem);
    }.bind(this));
};


var instance = new ChildClass({
  validity: [{
    valid: "01/01/17"
  }]
});

console.log(instance);
&#13;
&#13;
&#13;