call继承父级属性,prototype继承父级方法

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<body>
    
</body>
<script type="text/javascript" >
// 通过call继承父级属性
    function A(){
        this.abc=12
    }
   
 function B(){
    // this → new B();
    A.call(this)
 }
 var obj = new B();
alert(obj.abc) //12

// 通过prototype继承父级方法

A.prototype.show=function(){
    alert(this.abc)
}

B.prototype.show=A.prototype.show; //通过 prototype原型继承父级方法

obj.show() //12
</script> </html>
复制代码
 有先后顺序 先 继承 属性 再方法 否者 报错 说 那个  .call() 继承没有 这个 function

综合实例

实现效果 car.getInfo() 打印出 'car has 2 doors'  

复制代码
涉及到的知识点 继承 和 修改继承到的 属性以及方法
function vehicle(){
this.door=4; } function car (){ } vehicle.prototype ={ getName: function(){ return 'vehicle' }, getInfo: function(){ return [ this.getName(),'has',this.door,'doors' ].join(',') } }
复制代码

结果

  car.prototype = new vehicle(); // car 继承 wehicle 原型 的方法

  var car1 = new car(); // 实例化
  car1.door=2;//修改 原型值
  car1.getName=function (){ //修改  vehicle 原型中的 getName 方法
       return 'car'
  }
  console.log(car1.getInfo()) //实现效果 car.getInfo() 打印出 'car has 2 doors'

 

posted @   xuanPhoto  阅读(222)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示