首页 > web前端 > js教程 > 正文

详细介绍javascript使用prototype实现OOP继承的方法

黄舟
发布: 2017-03-18 15:04:36
原创
1260 人浏览过

使用prototype特性,可以很方便的在子类中继承父类的方法和属性

下例中Vegetable视为父类,Celery视为子类。

Vegetable 拥有属性taste, 方法fun1

Celery 拥有属性 color, 方法fun2,如果再定义与Vegetable 中同名的属性或方法,则会覆盖父类Vegetable 中对应的属性和方法。

function Vegetable(){
	this.taste='delicious';
	
	this.fun1 = function(){
		alert('Vegetable fun1 doing...');
	}
}

function Celery(){
	this.color = 'green';	
	this.taste = 'bad';
	this.fun1 = function(){
		alert('Celeryfun1 doing...');
	}
	this.fun2 = function(){
		alert('Celery fun2 doing...');
	}		
}

Celery.prototype = new Vegetable();
var stick = new Celery();
var polymorphed = stick.taste;

alert(polymorphed);
alert(stick.color);

stick.fun1();
stick.fun2();
登录后复制

以上是详细介绍javascript使用prototype实现OOP继承的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!