今天文章会延续昨天的程序码去做建构式的学习纪录
我们先看看原本的程序码:
var player=new Object;
player.name="John";
player.hp=100;
player.fight=function(){
this.hp=this.hp-2
};
player.rest=function(){
this.hp++
}
};
player.report=function(){
alert(this.name+":"+this.hp)
};
player.fight();
player.rest();
player.report();
这上方指的是John这个角色的部分,如果用上方的程序码要再建立新的角色,就需要重复上面程序码,只是换个角色或是名称,但是一但角色多了之後,整个程序码就会变成有点混乱,这时候我们可以使用建构式去作出一个模板,接下来要创立新角色就只要套用模板就可以了,方法如下:
function player (name,hp){
this.name=name;
this.hp=hp;
this.fight=function(){
this.hp-=2
};
this.rest=function(){
this.hp++
};
this.report=function(){
alert(this.name+":"+this.hp)
};
}
我们可以看到上方做出了基本的模板出来,function player就是我们设定要用来建构物件的函式,内容就是我们规划出来的样板,使用this建立新建的空白物件,接着我们要来使用这个样板,使用方式如下:
var player = new player("John", 100); //输入资料丢回函式
player.fight(); //呼叫内部函式
player.report(); //呼叫内部函式
var player2= new player("Bob", 80);
player2.rest();
player2.report();
参考来源:
https://wcc723.github.io/javascript/2017/12/18/javascript-constructor/
https://www.youtube.com/watch?v=xSu7TbPPy34
>>: 30天学会 Python-Day25: 今晚,我想来点...
import React , {useState} from 'react'; const For...
前言 回圈基本上是每个程序语言必备的函式,藉以回圈来达成反覆或是循环的动作。而 Go 语言的回圈种类...
此篇会介绍三种免费的 sass 编译方法。 Live Sass Compiler 这是一款免费 V...
Chap.I 理论基础 Part 1:线性代数 1. Getting Started with Eq...
大家好,我是YIYI,今天我要来制作日记部分的介面。 如何进入日记页面? 日记的部分是点选像是笔的i...