您的位置:首页 > Web前端 > JavaScript

javascript 使用prototype 实现OOP继承

2011-09-29 11:49 661 查看
使用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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: