JS原型與繼承操作示例
本文實(shí)例講述了JS原型與繼承操作。分享給大家供大家參考,具體如下:
<script> var Beverage = function(){}; Beverage.prototype.boilWater = function(){ console.log("把水煮沸"); }; Beverage.prototype.brew = function(){ throw new Error("子類(lèi)必須重寫(xiě)該方法"); }; Beverage.prototype.pourInCup = function(){ throw new Error("子類(lèi)必須重寫(xiě)該方法"); }; Beverage.prototype.addCondiments = function(){ throw new Error("子類(lèi)必須重寫(xiě)該方法"); }; 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();//繼承父類(lèi)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();//繼承父類(lèi)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)問(wèn)需要加調(diào)料嗎?"); }; var coffee = new Coffee();//實(shí)例化Coffee coffee.init(); var tea = new Tea();//實(shí)例化Tea tea.init(); </script>
這里使用在線(xiàn)HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試運(yùn)行結(jié)果如下:
更多關(guān)于JavaScript相關(guān)內(nèi)容還可查看本站專(zhuān)題:《javascript面向?qū)ο笕腴T(mén)教程》、《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)文章
canvas 畫(huà)布在主流瀏覽器中的尺寸限制詳細(xì)介紹
這篇文章主要介紹了canvas 畫(huà)布在主流瀏覽器中的尺寸限制詳細(xì)介紹的相關(guān)資料,canvas在不同瀏覽器下面有不同的最大尺寸限制,這里測(cè)試下,需要的朋友可以參考下2016-12-12獲取url中用&隔開(kāi)的參數(shù)實(shí)例(分享)
下面小編就為大家?guī)?lái)一篇獲取url中用&隔開(kāi)的參數(shù)實(shí)例(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05微信小程序自定義組件實(shí)現(xiàn)tabs選項(xiàng)卡功能
這篇文章主要為大家詳細(xì)介紹了微信小程序自定義組件實(shí)現(xiàn)tabs選項(xiàng)卡功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07JavaScript前端實(shí)現(xiàn)壓縮圖片功能
這篇文章主要介紹了JavaScript前端實(shí)現(xiàn)壓縮圖片功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(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è)簡(jiǎn)易的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)一個(gè)簡(jiǎn)易的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04