首页 > 解决方案 > 原型继承如何影响 JavaScript 中的方法覆盖?

问题描述

这是代码,

function extend(child, parent) {
  child.prototype = Object.create(parent.prototype);
  child.prototype.constructor = child
}

//Super Class
var Mobile = function() {}

//Prototype Method
Mobile.prototype.show = function() {
  return "Super Class Method";
}

//Sub class 
var Samsung = function() {}

extend(Samsung, Mobile);
Samsung.prototype.show = function() {
  return "Sub Class Method";
}

var sam = new Samsung();
document.write(sam.show()); //displays "Sub Class Method"

function extend(child, parent) {
  child.prototype = Object.create(parent.prototype);
  child.prototype.constructor = child
}

//Super Class
var Mobile = function() {}

//Prototype Method
Mobile.prototype.show = function() {
  return "Super Class Method";
}

//Sub class 
var Samsung = function() {}
Samsung.prototype.show = function() {
  return "Sub Class Method";
}

extend(Samsung, Mobile);

var sam = new Samsung();
document.write(sam.show()); //displays "Super Class Method"

当我在为三星初始化原型方法 show() 之前使用 Mobile.prototype 扩展 Samsung.prototype 时,我看到了 Samsung.prototype 的 show() 方法,但是在初始化之后编写它为我提供了 Mobile 的 show() 方法。原型。有人可以解释为什么会发生这种情况,因为我是 JavaScript 新手吗?

标签: javascript

解决方案


注意第一个代码片段:

这种模式称为behavior delegation,父原型和子原型使用您的extend函数链接在一起,它们不是彼此的副本,它们是相同的,但是当您为原型链中已经存在的属性分配新值时,您会隐藏它和新值将在您请求时使用,而不是父原型中的值。

在为子对象创建show方法后的第二个代码片段中,您重新覆盖了整个原型对象,这是正常结果,因为您手动使其原型指向新的父原型。


推荐阅读