码迷,mamicode.com
首页 > Web开发 > 详细

js面向对象继承

时间:2018-04-28 14:17:17      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:app   特征   pre   this   原型链   封装   1.0   error:   min   

                      js的面向对象变成其实是基于对象的开发(js是没有累的概念);

1:任何基于对象的变成都有三个特征,抽象封装,继承,多态。

  1 抽象封装:抽象指抽取对象的属性和行为(方法),然后有机的结合在一起,这个过程叫做封装,结果就是只对外提供接口(通过this创建共有属性共有方法),而隐藏内部的实现(共有方法可以调用私有的方法)。

  2 :继承:子类实现拥有父类的属性和方法的过程称之为继承;常用的继承凡事如下两种。

      1:call或者apply    

        function F(x){

 

            this.x=x

 

            this.sayX=function(){

 

             alert(this.x)

 

            }

 

           }

           function Y(x){

 

            F.call(this,x);

 

           //F.apply(this,agruments);

 

             }

 

           var t=new Y(2);

 

          alert(t.sayX())//2

 

        注意??:call apply是无法调用

        

        function F(x){

            this.x=x

          }

          F.prototype.sayX=function(){

 

              alert(this.x)

 

          }

 

         function Y(x){

 

            F.call(this,x);

             }

 

           var t=new Y(2);

 

          alert(t.sayX())//new_file.html?__hbt=1524886368955:91 Uncaught TypeError: t.sayX is not a function

 

       2 原型链继承

       function Person(name, sex){

            this.name=name;

            this.sex=sex;

      }

        Person.prototype.showName=function(){

            alert(this.name);

       }

        Person.prototype.showSex=function(){

              alert(this.sex);

      }

        function worker(name,sex,job){

            this.job=job;

          Person.apply(this,arguments)//获取公有的属性

       }

        worker.prototype=new Person()

        worker.prototype.sayJob=function(){

          alert(this.job)

        }

        var n=new worker(‘xxw‘,‘nan‘,‘chenguxyuan‘);

        console.log(n)

        alert(n.showName())//xxw

        alert(n.showSex())//nan

        alert(n.sayJob())//chenguxyuan

3 多态

      js 天然支持多态度

       通过判断参数argumrnts还有若数据类型,赋值什么数据就是什么数据

 

    

    

js面向对象继承

标签:app   特征   pre   this   原型链   封装   1.0   error:   min   

原文地址:https://www.cnblogs.com/ypwei/p/8966822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!