美文网首页
JS继承问题

JS继承问题

作者: 雅玲哑铃 | 来源:发表于2017-12-21 20:38 被阅读12次

    JS作为面向对象的弱类型语言,继承也是其非常强大的特性之一,那么,我们该如何在JS中实现继承呢?

    一、公有私有属性

    //定义一个类
    function Person(name){
        var name  = name;      //private 私有属性
        this.height = "180cm";   //public 公有属性
    }
    

    首先,在这个类里面,我们设置了两种属性,公有属性才能在外部访问,私有属性访问不到,我们可以来测试一下,实例化一个对象:

    var newPerson = new Person("张三");
    console.log(newPerson.name,newPerson.height);      //undefined  "180cm"
    

    这里我们打印不到newPerson.name,是因为var定义的name是类的私有变量,通过对象名.属性的方式不能被访问,私有属性只能在内部使用,而通过this.height是定义公有属性,可以在外部通过对象.属性名来访问;
      那么要怎样来访问私有属性和设置私有属性呢?

    function Person(name){
        var name  = name;      //private 私有属性
        this.height = "180cm";   //public 公有属性
        //通过公有方法访问私有属性
        this.get = function(){
            return name;
        }
        //设置私有属性
        this.set = function(newName){
            name = newName;  
        }
    }
    

    这里我们可以设置公有的方法,将私有属性当做返回值,再在外部调用公有方法获得私有属性,设置私有属性也是这个道理,通过外部调用公有方法,在公有方法中设置私有属性,这样就能在外部设置私有属性了。

    //外部我们这样调用公有方法
    console.log(newPerson.get());  //通过公有方法获得私有属性name
    newPerson.set("李四");   //通过公有方法设置私有属性name
    new
    

    二、继承问题

    说道继承,父类和子类都是必不可少的

    //定义一个父类
    function Dad(height){
        this.name = "张三";
        this.age = "50";
        this.height = height;
        this.money = "$1000000";
        this.hobby = function(){
          console.log("喜欢高尔夫");
        }
    }
    //定义一个子类
    function Son(height){
        //通过调用父类构造方法继承属性
        Dad.call(this,height);
        //Dad.apply(this,[height]);
        //Dad.bind(this)(height);
        this.action = function(){
            console.log("喜欢玩");
        }
    }
    //实例化对象
    var newSon = new Son("180cm");
    console.log(newSon.height);
    newSon.hobby();
    newSon.action();
    

    打印结果是如下,证明是可以在子类构造方法中调用父类构造方法来继承父类属性的


    打印结果.png

    相关文章

      网友评论

          本文标题:JS继承问题

          本文链接:https://www.haomeiwen.com/subject/uqqzwxtx.html