JavaScript面向对象中的封装和继承怎么实现(javascript,开发技术)

时间:2024-05-05 09:59:33 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

    1、面向对象

    【三大显著特征】:封装、继承、多态

    1、封装

    【解释】:封装的本质就是将有关联的代码组合在一起。

    【优势】:

    保证代码可以复用提高代码的维护效率

    【以前的封装方法】:

    函数封装

    functionfn(){}

    命名空间封装

    leto={name:'zhangsan',age:20}letobj={name:'lisi',age:18}

    【新的封装方法】:

    构造函数

    //自定义构造函数functionPerson(name,age,height,weight){ this.name=name; this.age=age; this.height=height; this.weight=weight; //方法 this.eat=function(){ console.log('吃饭') } this.sleep=function(){ console.log('睡觉') }}//实例化一个对象letobj1=newPerson('zhangsan',20,'198cm','60kg')console.log(obj1)letobj2=newPerson('lisi',24,'168cm','70kg')console.log(obj2)

    【总结】:

    构造函数体现了面向对象的封装特性构造函数实例创建的对象彼此独立、互不影响命名空间式的封装无法保证数据的独立性

    2、原型对象

    【解释】:本质是构造函数的一个属性,prototype的是对象类据类型,称为构造函数的原型对象。

    【代码示例】:

    functionPerson(name,age){this.name=namethis.age=age//this.sing=function(){ //console.log('唱歌') //}}console.log(Person.prototype);Person.prototype.sing=function(){console.log('唱歌')}letp1=newPerson('zhangsan',20);console.log(p1)p1.sing()

    【总结】:

    • 只要是构造函数就有原型对象

    • 原型对象中的方法,实例对象可以直接调用

    • 原型对象和构造函数都有相同的方法的时候就使用构造函数本身的方法

    【constructor属性】:代表了该原型对象对应的构造函数。

    【示例】:

    functionPerson(name,age){ this.name=name this.age=age}console.log(Person.prototype,constructor)

    【图解】:

    JavaScript面向对象中的封装和继承怎么实现

    【__proto__属性】:用于指向原型对象

    【示例】:

    functionPerson(name,age){ this.name=name this,age=age}Person.prototype.eat=function(){ console.log('吃饭')}letperson1=newPerson('张三',22);console.log(person.__proto__===Person.prototype)

    3、继承

    【封装问题引出】:

    //封装中国人的行为特征functionChinese(){//中国人的特征this.arms=2;this.legs=2;this.eyes=2;this.skin='yellow';this.language='中文';//中国人的行为this.walk=function(){}this.sing=function(){}this.sleep=function(){}}//封装日本人的行为特征functionJapanese(){//日本人的特征this.arms=2;this.legs=2;this.eyes=2;this.skin='yellow';this.language='日文';//日本人的行为this.walk=function(){}this.sing=function(){}this.sleep=function(){}}

    【总结】:其实我们都知道无论是中国人、日本人还是其它民族,人们的大部分特征是一致的,然而体现在代码中时人的相同的行为特征被重复编写了多次,代码显得十分冗余,我们可以将重复的代码抽离出来

    【代码改写】:

    <script>//所有人functionPerson(){//人的特征this.arms=2;this.legs=2;this.eyes=2;//人的行为this.walk=function(){}this.sing=function(){}this.sleep=function(){}}//封装中国人的行为特征functionChinese(){//中国人的特征this.skin='yellow';this.language='中文';}//封装日本人的行为特征functionJapanese(){//日本人的特征this.skin='yellow';this.language='日文';}//human是构造函数Person的实例lethuman=newPerson();//中国人Chinese.prototype=newPerson();Chinese.prototype.constructor=Chinese;//日本人Japanese.prototype=human;Japanese.prototype.constructor=Japanese;
     </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
    本文:JavaScript面向对象中的封装和继承怎么实现的详细内容,希望对您有所帮助,信息来源于网络。
    上一篇:css层叠上下文怎么实现下一篇:

    6 人围观 / 0 条评论 ↓快速评论↓

    (必须)

    (必须,保密)

    阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18