原型方法未被覆盖

Prototype method not being overriden

本文关键字:覆盖 方法 原型      更新时间:2023-09-26

为什么控制台中没有记录foo?我假设foo基方法将被子方法覆盖。为什么不是这样?

function parent(){ }
parent.prototype.foo = function(){ 
    console.log('foobar');
};
function child(){ }
child.prototype.foo = function(){ 
    console.log('foo');
};
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
console.log(new child().foo()); // foobar

进行时

child.prototype = Object.create(parent.prototype)

替换先前添加了foo特性的对象。

只需更改顺序即可稍后设置foo值:

function parent(){ }
parent.prototype.foo = function(){ 
    console.log('foobar');
};
function child(){ }
child.prototype = Object.create(parent.prototype);
child.prototype.foo = function(){ 
    console.log('foo');
};
child.prototype.constructor = child;
console.log(new child().foo()); // foo