您好,登錄后才能下訂單哦!
小編給大家分享一下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)問(wèn)需要加調(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測(cè)試運(yùn)行結(jié)果如下:
以上是“JS原型與繼承操作的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。