var Beverage = function(){} Beverage.prototype.boilWater = function(){ console.log("煮沸水"); }; Beverage.prototype.brew = function(){ // console.log("冲泡饮料"); throw new Error("子类必须重写该方法"); }; Beverage.prototype.putInCup = function(){ // console.log("倒进杯中"); throw new Error("子类必须重写该方法"); }; Beverage.prototype.addCondiments = function(){ // console.log("添加辅料"); throw new Error("子类必须重写该方法"); }; Beverage.prototype.customIsWant = function(){ // 演示钩子方法 return true; } Beverage.prototype.init = function(){ this.boilWater(); this.brew(); this.putInCup(); if(this.customIsWant()){ this.addCondiments(); } } var Coffee = function(){} Coffee.prototype.brew = function () { console.log("用开水冲泡咖啡"); } Coffee.prototype.putInCup= function () { console.log("把咖啡倒进杯子里"); } Coffee.prototype.addCondiments= function () { console.log("加糖和牛奶"); } Coffee.prototype.customIsWant = function(){ return false; } var Tea = function(){} Tea.prototype.brew = function () { console.log("用开水冲泡茶"); } Tea.prototype.putInCup= function () { console.log("把茶倒进杯子里"); } Tea.prototype.addCondiments= function () { console.log("加柠檬"); } Tea.prototype.customIsWant = function(){ return window.confirm("请问需要加柠檬吗?"); } // js的继承 Coffee.prototype = new Beverage(); Tea.prototype = new Beverage(); var coffee = new Coffee(); console.log(coffee.brew()); coffee.init(); var tea = new Tea(); tea.init();
这里就举这个coffe的例子了,应该是要先继承父类,再重写父类的方法。
var Beverage = function(){}; Beverage.prototype.boilWater = function(){ console.log("把水煮沸"); }; Beverage.prototype.brew = function(){ throw new Error("子类必须重写该方法"); }; Beverage.prototype.pourInCup = function(){ throw new Error("子类必须重写该方法"); }; Beverage.prototype.addCondiments = function(){ throw new Error("子类必须重写该方法"); }; Beverage.prototype.customerWantsCondiments = function(){ return true; }; Beverage.prototype.init = function(){ this.boilWater(); this.brew(); this.pourInCup(); if(this.customerWantsCondiments){ this.addCondiments(); } }; var Coffee = function(){}; Coffee.prototype = new Beverage();//应该是先继承父类,之后再重写方法 Coffee.prototype.boilWater = function(){ console.log("把水煮沸"); }; Coffee.prototype.brew = function(){ console.log("用沸水冲泡咖啡"); }; Coffee.prototype.pourInCup = function(){ console.log("把咖啡倒进杯子"); }; Coffee.prototype.addCondiments = function(){ console.log("加糖和牛奶"); }; var coffee = new Coffee(); coffee.init();