JS原型與繼承操作示例
更新時間:2019年05月09日 11:29:26 作者:Yxh_blogs
這篇文章主要介紹了JS原型與繼承操作,涉及javascript面向?qū)ο蟪绦蛟O(shè)計中原形與繼承的相關(guān)定義、實例化操作技巧,需要的朋友可以參考下
本文實例講述了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("請問需要加調(diào)料嗎?"); }; var coffee = new Coffee();//實例化Coffee coffee.init(); var tea = new Tea();//實例化Tea tea.init(); </script>
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試運行結(jié)果如下:
更多關(guān)于JavaScript相關(guān)內(nèi)容還可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。