示例参考 - ES5
<script>
function Student(name, subjects) {
this.name = name;
// ...
// 如果是文科生:['政治', '历史', '地理']
// 如果是理科生:['数学', '物理', '化学']
this.subjects = subjects;
}
/**
* 创建学生
* @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, ['数学', '物理', '化学'])
break;
case '体育':
return new Student(name, ['长跑', '...'])
break;
default:
throw '没有这个专业,别瞎填';
}
}
var whh = factory('王花花', '文科');
var lsd = factory('李拴蛋', '理科');
var zks = factory('赵可爽', '体育');
var lbb = factory('刘备备', '撒盐');
console.log(whh);
console.log(lsd);
console.log(zks);
</script>
示例参考 - ES6
<script>
class Student {
constructor(name, subjects) {
this.name = name;
// ...
// 如果是文科生:['政治', '历史', '地理']
// 如果是理科生:['数学', '物理', '化学']
this.subjects = subjects;
}
}
/**
* 创建学生
* @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, ['数学', '物理', '化学'])
break;
case '体育':
return new Student(name, ['长跑', '...'])
break;
default:
throw '没有这个专业,别瞎填';
}
}
const whh = factory('王花花', '文科');
const lsd = factory('李拴蛋', '理科');
const zks = factory('赵可爽', '体育');
const lbb = factory('刘备备', '撒盐');
console.log(whh);
console.log(lsd);
console.log(zks);
</script>
登录后评论