为什么nodejs不能inheritance浏览器js
我有两个构造函数,子从父inheritance一些方法和属性,它只是这样的东西
function foo(){ this.bar="baz"; } function fubar(){ this.qux="zubar"; } fubar.prototype=new foo(); fubar.prototype.constructor=fubar; module.exports.fubar=fubar;
里面的文件inheritance工作正常,但是当它被导出不能达到父母的元素我已经尝试util.inherits
以及结果是相同的
你只需要从fubar
构造函数中调用foo
构造函数,这样.bar
属性就可以在foo
构造函数中正确初始化了:
function foo(){ this.bar = "baz"; } function fubar(){ foo.call(this); this.qux = "zubar"; } fubar.prototype = Object.create(foo.prototype); fubar.prototype.constructor = fubar; module.exports.fubar = fubar;
原型使用Object.create()
也更好,尽pipe你曾经工作过。