当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS原型与继承操作示例

JS原型与继承操作示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js原型与继承操作。分享给大家供大家参考,具体如下:

<script>
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();//继承父类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 tea = function(){};
tea.prototype = new beverage();//继承父类beverage
tea.prototype.boilwater = function(){
  console.log("把水煮沸");
};
tea.prototype.brew = function(){
  console.log("用沸水浸泡茶叶");
};
tea.prototype.pourincup = function(){
  console.log("把茶水倒进杯子");
};
tea.prototype.addcondiments = function(){
  console.log("加入柠檬");
};
tea.prototype.customerwantscondiments = function(){
  return window.confirm("请问需要加调料吗?");
};
var coffee = new coffee();//实例化coffee
coffee.init();
var tea = new tea();//实例化tea
tea.init();
</script>

这里使用在线html/css/javascript代码运行工具:测试运行结果如下:

更多关于javascript相关内容还可查看本站专题:《javascript面向对象入门教程》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网