美文网首页
Javascript 构造函数与类课后作业

Javascript 构造函数与类课后作业

作者: abrila | 来源:发表于2018-11-19 15:52 被阅读0次

    1Vehicle,具有seats属性和drive方法

    class Vehicle{
        constructor(seats){ this.seats=seats;}
        driver(){
            console.log("i am driving");
        }
    }
    kk = new Vehicle('ii');
    console.log(kk.seats);
    kk.driver();
    

    或者:

    class Vehicle{
        constructor(seats,driver){
            this.seats=seats;
            this.driver = driver;
        }
    }
    kk = new Vehicle('ii',function() {
    console.log("iuiuiui");})
    console.log(kk.seats);
    kk.driver();
    

    答案

    ii
    i am driving
    

    其中第一种实现方法可以实现在类中定义方法,对象直接调用即可实现功能;第二种方法可以实现对象可以自己定义方法里面要实现的功能
    2Bus继承Vehicle,扩展了stops属性和charge方法`

    class Bus extends Vehicle {
            constructor(stop) {
                super();
                this.stop = stop;
            }
    
            charge() {
                console.log("i will receive you really high")
            }
        }
    

    3. 把上述类的写法⽤用构造函数的写法再实现一次
    重写问题1的代码如下:

    
        function Vehicle(seats) {
            this.seats = seats;
            this.driver = function (way) {
                console.log(way);
            }
        }
    
        vihi = new Vehicle(9);
        console.log(vihi.seats)
        vihi.driver("riding");
    
    

    重写问题2的代码如下:

    function Bus(stops){
        this.stops = stops;
        this.charge = function(money){
            console.log("give me"+ ' '+money);
        }
    }
    Bus.prototype = {
         drive : function (way) {
            console.log(way);
        },
        seats:"oo"
    }
    bus = new Bus("right now");
    console.log(bus.stops);
    bus.charge("50$");
    console.log(bus.seats);
    bus.drive("riding");
    

    答案为:

    right now
    give me 50$
    oo
    riding
    

    相关文章

      网友评论

          本文标题:Javascript 构造函数与类课后作业

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