Jac*_*Guy 5 javascript inheritance prototype
我有一个从另一个对象继承的对象,如下所示:
var a = function ()
{
}
a.prototype.foo = function ()
{
bar();
}
var b = function ()
{
a.call(this)
}
b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;
Run Code Online (Sandbox Code Playgroud)
我想要一个 b 的方法,它也被命名为“foo”并使用相同的名称扩展 a 的函数。
b.prototype.foo = function ()
{
baz();
// When .foo() is called, runs both bar() and baz()
}
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法可以在不借助库的情况下在原生 JavaScript 中完成此操作?
小智 4
如果我理解正确的话你可以扩展这个方法
function A() {}
A.prototype.foo = function() {
console.log('foo');
};
function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.foo = function() {
A.prototype.foo.call(this);
console.log('foo2');
}
var b = new B();
b.foo();Run Code Online (Sandbox Code Playgroud)