Javascript:向要继承的父类/添加方法

Javascript:向要继承的父类/添加方法,javascript,object,Javascript,Object,我想在定义了子类B之后,在父类a中添加一个方法“bar”,以便继承该方法。可能吗 我尝试了以下代码 function A() { this.foo = function () { console.log('foo') } } function B() { A.call(this) } // (trying to) add a new method to A A.prototype.bar = function () { console.log('bar

我想在定义了子类B之后,在父类a中添加一个方法“bar”,以便继承该方法。可能吗

我尝试了以下代码

function A() {
   this.foo = function () {
       console.log('foo')
   }
}
function B() {
   A.call(this)
}

// (trying to) add a new method to A

A.prototype.bar = function () {
    console.log('bar');
}

// It works with instances of A
var a = new A()     
a.foo()            // ok
a.bar()            // ok

// but not with an instance of B
var b = new B()     
b.foo()            // this works
b.bar()            // not this one <------

/*  
   Exception: b.bar is not a function
   @Scratchpad/3:17:1
*/
函数A(){
this.foo=函数(){
console.log('foo')
}
}
函数B(){
打电话(这个)
}
//(正在尝试)将新方法添加到
A.prototype.bar=函数(){
console.log('bar');
}
//它适用于
var a=新的a()
a、 foo()//好的
a、 bar()//好的
//但不适用于B的实例
var b=新的b()
b、 foo()//这很有效

b、 bar()//不是这个如果您只需要修复代码,可以链接如下方法:

function B() {
   A.call(this)
   for(var i in A.prototype){ this[i] = A.prototype[i]; }
}
但我认为这是一种糟糕的方式

function A() {
   this.foo = function () {
       console.log('foo');
   };
}
function B() {
   A.call(this);
}

// (trying to) add a new method to A

A.prototype.bar = function () {
    console.log('bar');
};
B.prototype = Object.create(A.prototype);
// It works with instances of A
var a = new A()  ;   
a.foo()  ;          // ok
a.bar()  ;          // ok

// but not with an instance of B
var b = new B() ;    
b.foo()   ;         // this works
b.bar()  ;
对于函数类型的继承,您不能添加类中不存在的方法。使用您缺少的原型:

B.prototype.__proto__ = A.prototype
如果您不喜欢使用
\uuuuu proto\uuuu
,您可以使用:

B.prototype = Object.create(A.prototype);

如果您不希望后一种行为能够在事后编辑原型,请使用下划线或lodash等提供该功能的工具:

function newA() {
    return Object.create(Object.assign({}, A));
}

因为
a
b
不是同一类的实例..你可以做
Object.prototype.bar=function(){..}
将其添加到所有对象中,但是画笔可能比你想要的
Object.setPrototypeOf()要宽得多,但这是针对新浏览器的:-@RoyiNamir这里有一个问题-如果你关心性能,你应该避免设置对象的[[Prototype]]。相反,使用object.create()创建一个具有所需[[Prototype]]的新对象@沙本克:是的。但是请继续阅读:Object.setPrototypeOf()在最新的ECMAScript 6标准草案中。它通常被认为是设置对象原型的正确方法,而不是设置更具争议性的对象。原型。原型属性。我认为一开始的红色警报谈论的是
\uuuuuuuuuuuu
之类的东西。好。。。。不管怎样,我还是会使用这个标准。它是可行的,但是在扩展父类之后“修复”子类有它的缺点。可以有很多子类…设置
\uuuuu proto\uuuuu
是不受鼓励的(我不是dv)@RoyiNamir true,你也可以使用
对象。create()
,我想
\uuuuu proto\uuu
是老派:pYes:-)。我不认为它将永远是100%过时的。似乎是我一直在寻找的。非常感谢大家。您不能重写子类中的某些内容并在父类中使用静态方法吗?分别呼叫A和B的酒吧恐怕我不明白。你能解释一下你的意思吗?
function newA() {
    return Object.create(Object.assign({}, A));
}