2018年3月25日 星期日

建構函數建構物件

建構函數可以用來定義 物件的屬性和方式:

 <p id="output"></p>

第一步:建立物件屬性

function mycar(name,ID,size,age){
        this.name=name;
        this.ID=ID;
        this.size=size;
        this.age=age;
};

name, ID, size, age的參數是用來建立物件的屬性值, this 指的是物件本身.

第二步:建立物件
利用new來建立物件.
var car= new mycar('Jason',3345678,'33cm',26); //這樣的方式是 mycar 直接傳入物件的屬性值.

or
var car=new mycar();
car.name="Jason";
car.ID=3345678;
car.size="33cm";
car.age=26;

第三步:建立物件方法

function mycar(name,ID,size,age){
        this.name=name;
        this.ID=ID;
        this.size=size;
        this.age=age;
        this.print=printCar;

};

function printCar(){
       document.getElementById('output').innerHTML=this.name+'<br>'+this.ID+'<br>'+
       this.size+'<br>'+this.age;

};

car.print();


output:

Jason
3345678
33cm
26


沒有留言:

張貼留言