关于js的模板方法模式的讲解

不言
Lepaskan: 2018-07-14 17:23:01
asal
1702 orang telah melayarinya

这篇文章主要介绍了关于js的模板方法模式的讲解,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

* 分离出共同点

function Beverage() {}

Beverage.prototype.boilWater = function() {
	console.log("把水煮沸");
}

Beverage.prototype.brew = function() {
	throw new Error('子类必须重写brew方法');
}

Beverage.prototype.pourInCup = function() {
	throw new Error('子类必须重写pourInCup方法');
}

Beverage.prototype.addCondiments = function() {
	throw new Error('子类必须重写addCondiments方法');
}

Beverage.prototype.init = function() {
	this.boilWater();
	this.brew();
	this.pourInCup();
	this.addCondiments();
}

function Coffee() {}

Coffee.prototype = new Beverage();

Coffee.prototype.brew = function() {
	console.log("用沸水冲泡咖啡");
}

Coffee.prototype.pourInCup = function() {
	console.log("把咖啡倒进杯子");
}

Coffee.prototype.addCondiments = function() {
	console.log("加糖和牛奶");
}

var coffee = new Coffee();
// coffee的原型Coffee没有init方法, 
// 顺着原型链委托给父类的Beverage原型上的init方法
coffee.init();

console.log("-------------------------");

function Tea() {}

Tea.prototype = new Beverage();

Tea.prototype.brew = function() {
	console.log("用沸水浸泡茶叶");
}

Tea.prototype.pourInCup = function() {
	console.log("把茶水倒进杯子");
}

Tea.prototype.addCondiments = function() {
	console.log("加柠檬");
}

var tea = new Tea();
tea.init();
Salin selepas log masuk

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何通过Vue.js使用Font Awesome实现小图标

关于js数组filter的用法

Atas ialah kandungan terperinci 关于js的模板方法模式的讲解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!