[想试试看JavaScript ] 物件 建构式

昨天做了一个 player 的物件范例

var player=new Object();
player.hp=100;
player.name="Abby";
player.fight=function(){
    this.hp=this.hp-2;
}
player.rest=function(){
    this.hp++;
}
player.report=function(){
    alert(this.name+": "+this.hp)
}

这样就可以制作的一个简单的物件来放置一个玩家的资料
不过如果需要第二个玩家的资料的话,就又需要 new 一个 Object

var player2=new Object();
player2.hp=100;
player2.name="Jane";
player2.fight=function(){
    this.hp=this.hp-2;
}
player2.rest=function(){
    this.hp++;
}
player2.report=function(){
    alert(this.name+": "+this.hp);
}

那有没有比较方便的方法呢?
有!!

建构式

设计建构式

我们可以使用function来建立建构式

function Player(){ // 建构式名称习惯使用大写,这是个命名习惯,方便让其他人一看知道这是一个建构式
    this.name="John";
    this.hp=100;
    this.fight=function(){
        this.hp=this.hp-2;
    }
    this.rest=function(){
        this.hp++;
    }
    this.report=function(){
        alert(this.name+": "+this.hp);
    }
}

使用建构式建立新物件

接着我们就可以利用这个建构式来建立新的物件

var player=new Player();

并且这个新的物件一样可以使用,我们设计的 fight 方法

player.fight();
player.rest();
player.report();

我们可以使用建构式建立其他新的的物件
并且这两个物件互相不影响

var player=new Player();
player.fight();
player.rest();
player.report();

var player2=new Player();
player2.fight();
player2.repot();

player 会回报 "John: 99"
player2 会回报 "John: 98"

增加参数

那我想要增加程序码弹性,让我可以不要每次建立新物件时,player.name 都是 john
可以使用参数

function Player(name,hp){ // 建构式名称习惯使用大写,这是个命名习惯,方便让其他人一看知道这是一个建构式
    this.name=name; // 参数会传进这里
    this.hp=hp;     // 参数会传进这里
    this.fight=function(){
        this.hp=this.hp-2;
    }
    this.rest=function(){
        this.hp++;
    }
    this.report=function(){
        alert(this.name+": "+this.hp);
    }
}

增加参数 name 与 hp
修改 this.name="John" 为 this.name=name
修改 this.hp=100 为 this.hp=hp
这样就修改好建构式

接着就是在建立新物件时,设定参数,决定玩家要叫什麽名子

var player=new Player("Bob",50);
var player2=new Player("abby",100);

player.fight();
player.report();

player2.fight();
player2.report();

这样就完成使用建构式,快速建立新物件,并且可以给予弹性,利用参数让每个物件有不同的属性
这些新的物件在运作的时候以互相不会影响。


<<:  Day 14 关键字品质分数

>>:  应用 LINE Front-end Framework 轻松建立互动 (2)

Code Generator 结构

接续上一篇的 annotation processor 实作,我们的 annotation proc...

Day 12:145. Binary Tree Postorder Traversal

今日题目 题目连结:145. Binary Tree Postorder Traversal 题目主...

[Day 15] 牛刀小试-在Controller封装自己的Post API

(这边只先列出必要的参数,若想要想新增自订栏位供User使用,都可再去扩充原本的class,先不在这...

Data layer implementation (1)

在上一篇,我们把 Ktor client 加到 Dagger 的 object graph 内。现在...

D30 / 终於完赛啦!- 写写第一次参赛的感想

终。於。完。赛。啦! 今年是我第一次参加铁人赛,真的有种焠链後重生的感觉。高密度的技术研究、文字输出...