JS原型與繼承操作示例
本文實(shí)例講述了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("把咖啡倒進(jìn)杯子"); }; 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("把茶水倒進(jìn)杯子"); }; Tea.prototype.addCondiments = function(){ console.log("加入檸檬"); }; Tea.prototype.customerWantsCondiments = function(){ return window.confirm("請(qǐng)問需要加調(diào)料嗎?"); }; var coffee = new Coffee();//實(shí)例化Coffee coffee.init(); var tea = new Tea();//實(shí)例化Tea tea.init(); </script>
這里使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測試運(yùn)行結(jié)果如下:
更多關(guān)于JavaScript相關(guān)內(nèi)容還可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章
微信小程序自定義組件實(shí)現(xiàn)tabs選項(xiàng)卡功能
這篇文章主要為大家詳細(xì)介紹了微信小程序自定義組件實(shí)現(xiàn)tabs選項(xiàng)卡功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07JavaScript前端實(shí)現(xiàn)壓縮圖片功能
這篇文章主要介紹了JavaScript前端實(shí)現(xiàn)壓縮圖片功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03輕松實(shí)現(xiàn)js選項(xiàng)卡切換效果
這篇文章主要幫助大家輕松實(shí)現(xiàn)js選項(xiàng)卡切換效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09js實(shí)現(xiàn)一個(gè)簡易的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)一個(gè)簡易的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04