創(chuàng)建類模式
<table id="roster"></table>
<script>
var rootElement = document.getElementById('roster');
function Student(name, gender, score) {
this.name = name;
this.gender = gender;
this.score = score;
this.quality = 100;
this.mount();
}
Student.prototype.sumScore = function () {
return this.score + this.quality;
}
/**
* 將數(shù)據(jù)轉(zhuǎn)換為HTML并插入到表格中
*/
Student.prototype.mount = function () {
var tr = document.createElement('tr');
tr.innerHTML =
'<td>' + this.name + '</td>' +
'<td>' + this.gender + '</td>' +
'<td>' + this.score + '</td>' +
'<td>' + this.quality + '</td>' +
'<td>' + this.sumScore() + '</td>'
;
rootElement.appendChild(tr);
}
var whh = new Student('王花花', '男', 98);
var lsd = new Student('李拴蛋', '女', 50);
</script>
構(gòu)造模式
<script>
let studentCount = 0;
class Student {
}
class StudentBuilder {
constructor() {
this.student = new Student();
}
setName(name) {
this.student.name = name;
}
setGender(gender) {
if (gender != '男' && gender != '女')
throw '好玩不';
this.student.gender = gender;
}
setHairLength(hairLength) {
if (
(this.student.gender == '男' && hairLength > 1) ||
(this.student.gender == '女' && hairLength > 25)
) throw '回去剪頭';
this.student.hairLength = hairLength;
}
build() {
studentCount++;
console.log(studentCount);
return this.student;
}
}
const builder = new StudentBuilder();
builder.setName('王花花');
builder.setGender('男');
builder.setHairLength(1);
const whh = builder.build();
const builder2 = new StudentBuilder();
builder2.setName('李拴蛋');
builder2.setGender('女');
builder2.setHairLength(20);
const lsd = builder2.build();
console.log(lsd);
</script>
工廠模式
<script>
function Student(name, subjects) {
this.name = name;
// ...
// 如果是文科生:['政治', '歷史', '地理']
// 如果是理科生:['數(shù)學', '物理', '化學']
this.subjects = subjects;
}
/**
* 創(chuàng)建學生
* @param {string} name 姓名
* @param {string} type 文科還是理科
* @return {Student}
*/
function factory(name, type) {
switch (type) {
case '文科':
return new Student(name, ['政治', '歷史', '地理'])
break;
case '理科':
return new Student(name, ['數(shù)學', '物理', '化學'])
break;
case '體育':
return new Student(name, ['長跑', '...'])
break;
default:
throw '沒有這個專業(yè),別瞎填';
}
}
var whh = factory('王花花', '文科');
var lsd = factory('李拴蛋', '理科');
var zks = factory('趙可爽', '體育');
var lbb = factory('劉備備', '撒鹽');
console.log(whh);
console.log(lsd);
console.log(zks);
</script>