<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
function Beverage(){
}
Beverage.prototype.boilWater=function(){
console.log("把水煮沸");
}
/*这应该是泡的过程, 具体如何泡呢?其实是子类中实现的,我也不知道,茶叶还是咖啡*/
Beverage.prototype.brew=function(){
/*如果父类中没写内容的话,出现错误,所以我们这样处理了,抛出错误*/
try{
/* throw new Error(" 抛出一个错误,子类必须重写该方法,如果子类没有重写该方法呢,它就会调用父类的同样的名称的方法")*/
}catch(e){
console.log("error message:"+e);
}
}
/*这应该是泡的过程, 具体如何泡呢?其实是子类中实现的,我也不知道,茶叶还是咖啡的杯子里*/
Beverage.prototype.pourInCup=function(){
try{
}catch(e){
console.log("e:"+e);
}
}
/*添加题料也是在子类中实现,我们不知道,什么调料*/
Beverage.prototype.addCondiments=function(){
try{
}catch(e){
console.log("e:"+e);
}
}
/*钩子方法*/
Beverage.prototype.customerWantsCondiments=function(){
/*用户需不需要调料呢,我们就会true,false就行了*/
return true;/*我们的默认需要调料的,*/
}
Beverage.prototype.init=function(){
this.boilWater();
this.brew();
this.pourInCup();
/*我们呢模板方法中判断就可以了,如果我们返回的是真的话,加调料*/
if(this.customerWantsCondiments()){
this.addCondiments();
}
}
/*end Beverage*/
function Coffee(){
}
/*子类呢,这个煮沸的过程呢,我们在父类中已经做了*/
/*Coffee.prototype.boilWater=function(){
console.log("把水煮沸");
}
*/
/*如果你一旦你重写了该方法呢,不会调用父类的同名称方法,而是会调用你自己的你写的方法, 这时候子类方法覆盖了父类的方法,*/
/*如果这样的话呢出现,强制性的要求*/
/*如果泡一杯茶叶,不想到添加蒙呢,这个时候我们用到钩子方法呢 customerWantsCondiments*/
/*我们在父类中容易变化的地方放置一个钩子,那么就进要不要钩子呢,子类自己决定的*/
Coffee.prototype.brew=function(){
console.log("用沸水冲泡咖啡");
}
Coffee.prototype.pourInCup=function(){
console.log("把咖啡倒进杯子");
}
Coffee.prototype.addCondiments=function(){
console.log("加糖和牛奶");
}
/*如果这个时候,不加柠檬的茶叶呢*/
Coffee.prototype.init=function(){
//this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
/*end Coffee*/
function Tea(){
}
/*子类呢,这个煮沸的过程呢,我们在父类中已经做了*/
/*Tea.prototype.boilWater=function(){
console.log("把水煮沸");
}*/
Tea.prototype.steepTea=function(){
console.log("用沸水冲泡茶叶倒进杯子里");
}
Tea.prototype.pourInCup=function(){
console.log("把咖啡倒进杯子");
}
Tea.prototype.addCondiments=function(){
console.log("加柠檬");
}
/*如果这个时候不加柠檬的茶叶呢,重写一下刚才的方法*/
Tea.prototype.customerWantsCondiments=function(){
/*return false;就可以了,你不用false,用户弹一个确定按钮*/
return window.confirm("请问需要调料吗")
}
Tea.prototype.init=function(){
//this.boilWater();
this.steepTea();
this.pourInCup();
this.addCondiments();
}
/*end Tea*/
var beverage = new Beverage();
beverage.init();
var coffee = new Coffee();
coffee.init();
var tea = new Tea();
tea.init()
/*
子类如果想父类的方法呢? 我们还需要继承! 实例化一个父类的对象 new Beverage()
将他呢,赋值给我们子类 构造函数的原型; Coffee=new Beverage() ;
*/
/*
coffee 子类实例化出来的对象呢,其实就可以访问到我们的父类new Beverage()对象的方法了,
var coffee = new Coffee();
coffee.init();
因为呢它是通过原型连去访问的
Coffee.prototype = new Beverage();
Tea.prototype= new Beverage();
*/
</script>
打开App,阅读手记