使用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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号