为了账号安全,请及时绑定邮箱和手机立即绑定

Coffee.prototype = new Beverage(); 子类继承了父类,还是报错,怎么办?

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();


正在回答

1 回答

这里就举这个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();


2 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

Coffee.prototype = new Beverage(); 子类继承了父类,还是报错,怎么办?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号