javascript - 原型继承如何影响 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 新手吗?
解决方案
注意第一个代码片段:
这种模式称为behavior delegation
,父原型和子原型使用您的extend
函数链接在一起,它们不是彼此的副本,它们是相同的,但是当您为原型链中已经存在的属性分配新值时,您会隐藏它和新值将在您请求时使用,而不是父原型中的值。
在为子对象创建show
方法后的第二个代码片段中,您重新覆盖了整个原型对象,这是正常结果,因为您手动使其原型指向新的父原型。
推荐阅读
- spring-boot - 不同上下文的多次招摇
- java - 通过一对多搜索时出现rsql-jpa错误
- gitlab - Gitlab Runner 无法在 docker 执行器中运行 docker 命令
- postgresql - 我如何知道 bucardo 是否进行主到主或主到从复制
- php - 使用 IIS 在 Windows 服务器上上传 PHP 视频时出现 413 错误
- python - 如果有一个装饰器的参数,如何从装饰器的参数中删除 self 参数
- php - 总是遇到同样的问题:SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
- java - 启动 Unity 时应用程序崩溃 - 在 Android Studio 中测试时不会崩溃
- ios - 如何使用现代 UICollectionViewDiffableDataSource 支持自定义单元格重新排序?
- mysql - 如何为cadence创建mysql数据库