建構函式建立物件

weixin_30639719發表於2020-04-05
<script type="text/javascript">
        function Car(make,model,year,color,passengers,convertible,mileage){
            this.make=make;
            this.model=model;
            this.year=year;
            this.color=color;
            this.passengers=passengers;
            this.convertible=convertible;        
            this.mileage=mileage;
            this.started=false;//將屬性started初始化false
            this.start=function(){
                this.started=true;
            };
            this.stop=function(){
                this.started=false;
            };
            this.drive=function(){
                if (this.started) {
                    console.log(this.make+" " +this.model  +" does zoom zoom");
                } else {
                    alert("you are first");
                }
            };

        }
        var chevy1= new Car("chevy1","bel air1",1967,"red",2,false,20121);
        var chevy2= new Car("chevy2","bel air2",1967,"red",2,false,20122);
        var chevy3= new Car("chevy3","bel air3",1967,"red",2,false,20123);
        var chevy4= new Car("chevy4","bel air4",1967,"red",2,false,20124);
        var cars =  [chevy1,chevy2,chevy3,chevy4];
        for (var i = 0; i < cars.length; i++) {
            cars[i].start();
            cars[i].drive();
          
            cars[i].stop();
        }
    </script>

注意:建構函式命名是使用的是首字母大寫,目的是為了區分普通函式   

   屬性名和形參名不必相同,但通常相同 ,這是約定

   建構函式不用返回值return 本身會完成這項任務

        先有建構函式  再有物件

轉載於:https://www.cnblogs.com/xiaoxiao2017/p/7987387.html

相關文章