首页 > 其他分享 >实现方法继承 js 230220

实现方法继承 js 230220

时间:2023-02-20 11:02:53浏览次数:35  
标签:function 继承 gard 230220 Dog js 原型 Animal prototype

需求

让子对象可用父方法


让子构造指向父构造

实现方法继承 js 230220_子类


存在的问题

如果给子构造的原型添加独有方法

会影响到父构造的原型

与实际需求的逻辑不符合


问题复现代码:

function Animal() {
this.name = "动物"
}

Animal.prototype.show = function () {
console.log("我的名字叫" + this.name)
}

function Dog() {
// 在子构造中用call调一下父造方法,把子对象本身传过去
Animal.call(this)
}

// 让狗原型指向动物原型(行不通)
Dog.prototype = Animal.prototype

// 给狗添加看门的方法
// 如果给子构造的原型添加了方法
// 那么会影响到父类
// 子类不好添加自己的独有方法
Dog.prototype.gard = function () {
console.log("狗在看门")
}

var wc = new Dog()
wc.show()
wc.gard()

var ani = new Animal()
ani.gard()


解决办法

实现方法继承 js 230220_实例化_02


function Animal() {
this.name = "动物"
}

Animal.prototype.show = function () {
console.log("我的名字叫" + this.name)
}

// 实例化一个动物对象
var dog_proto = new Animal()

function Dog() {
// 在子构造中用call调一下父造方法,把子对象本身传过去
Animal.call(this)
}



// 让狗原型指向动物原型(行不通)
Dog.prototype = dog_proto

// 给狗添加看门的方法
// 如果给子构造的原型添加了方法
// 那么会影响到父类
// 子类不好添加自己的独有方法
Dog.prototype.gard = function () {
console.log("狗在看门")
}

var wc = new Dog()
// 输出狗的特有方法
wc.gard()

// 测一测动物是否受影响
var ani = new Animal()
ani.gard()



标签:function,继承,gard,230220,Dog,js,原型,Animal,prototype
From: https://blog.51cto.com/u_13137233/6067970

相关文章

  • 根据两点经纬度计算两点间距离 js
    getDistance(lat1,lng1,lat2,lng2){letradLat1=lat1*Math.PI/180.0;letradLat2=lat2*Math.PI/180......
  • JSR303字段校验规则(笔记)
    ###直接上示例代码引入依赖(如果项目中没有的话)<dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId>......
  • NodeJS:使用 superagent 和 cheerio 爬取网页
    安装依赖:npminstallsuperagentcheerio--save同步代码:constsuperagent=require('superagent')constcheerio=require('cheerio')constfs=require('fs')f......
  • JS 异步
    回调函数ES5:使用回调函数处理异步执行的结果setTimeout(()=>{console.log('1')setTimeout(()=>{console.log('2')setTimeout(()=>{console......
  • js得到当前窗口内的宽度和高度
    vars="";s+="\r\n网页可见区域宽:"+document.body.clientWidth;s+="\r\n网页可见区域高:"+document.body.clientHeight;s+="\r\n网页可见区域宽:"+document.......
  • JS字符串和json转换
    <head><scriptsrc="jquery-1.8.0.min.js"type="text/javascript"></script><scriptsrc="jquery.json-2.4.js"type="text/javascript"></script></head>varst......
  • JS 差集
    <htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="zh"lang="zh"dir="ltr"><scripttype="text/javascript">vararr1=[1,3,4,5,6,7,8];var......
  • JS取queryString
    String.prototype.GetValue=function(para){varreg=newRegExp("(^|&)"+para+"=([^&]*)(&|$)");varr=this.substr(this.indexOf("\?")+1).match(re......
  • 如何理解 少用继承,多用组合
    HeadFirst设计模式一书中,开篇就提到了这个有趣的点:  当我们想让鸭子能飞的时候,首先跳出来的想法是给鸭子类增加一个fly()方法,然后所有的子类直接继承完事;结果,有一个......
  • jsp开发基础
    1、什么时动态网页?指的是能够通过不同的操作返回不同的功能及数据,具有交互功能。常见的开发模式:B/S架构:游览器和服务器C/S架构:客户端和服务器B/S架构的执行原理:基于......