js 模板方法模式
2024-10-19 13:01:24
* 分离出共同点
function Beverage() {} Beverage.prototype.boilWater = function() {
console.log("把水煮沸");
} Beverage.prototype.brew = function() {
throw new Error('子类必须重写brew方法');
} Beverage.prototype.pourInCup = function() {
throw new Error('子类必须重写pourInCup方法');
} Beverage.prototype.addCondiments = function() {
throw new Error('子类必须重写addCondiments方法');
} Beverage.prototype.init = function() {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
} function Coffee() {} Coffee.prototype = new Beverage(); Coffee.prototype.brew = function() {
console.log("用沸水冲泡咖啡");
} Coffee.prototype.pourInCup = function() {
console.log("把咖啡倒进杯子");
} Coffee.prototype.addCondiments = function() {
console.log("加糖和牛奶");
} var coffee = new Coffee();
// coffee的原型Coffee没有init方法,
// 顺着原型链委托给父类的Beverage原型上的init方法
coffee.init(); console.log("-------------------------"); function Tea() {} Tea.prototype = new Beverage(); Tea.prototype.brew = function() {
console.log("用沸水浸泡茶叶");
} Tea.prototype.pourInCup = function() {
console.log("把茶水倒进杯子");
} Tea.prototype.addCondiments = function() {
console.log("加柠檬");
} var tea = new Tea();
tea.init();
最新文章
- c/c++优化结构控制
- JS数组操作示意图(shift,unshift,pop,push)
- JavaScript变量的作用域和函数的作用域的区别
- 8.9 CSS知识点2
- Android对话框之dismiss和cancel和hide区别
- 关于SQL表联接
- IntelliJ IDEA 15 安装
- linux bash shell中case语句的实例
- 关于bat文件语法
- 从运行原理及使用场景看Apache和Nginx
- JavaScript之二:this
- 关于web.xml中的<;welcome-file-list>;
- Swing-布局管理器之BorderLayout(边界布局)-入门
- 从Trie树到双数组Trie树
- centos6.5 redis搭建
- 查看Linux下的文件
- (转)C#中的那些全局异常捕获
- 用EXCLE群发outlook邮件
- C#DataTable 使用GroupBy方法的lamda 表达式和Linq语句写法
- IDEA开发常用快捷键