本文實例講述了javascript基於prototype實現類似OOP繼承的方法。分享給大家供大家參考,具體如下:
這裡要說明的是,公有屬性(使用this.修飾符)可以被覆蓋,私有屬性(使用var 修飾符)不能被覆蓋
子類不能訪問父類的私有屬性,父類的方法正常訪問父類的私有變量。
function Vegetable(){
this.taste='delicious';
var a = 'I\'m Vegetable\'a!'
this.fun1 = function(){
alert('Vegetable fun1 doing...');
}
this.fun3 = function(){
alert(a);
}
}
function Celery(){
var a = 'I\'m Celery\' a';
this.color = 'green';
this.taste = 'bad';
this.fun1a = function(){
alert('Celeryfun1 doing...');
}
this.fun2 = function(){
alert('Celery fun2 doing...');
}
this.fun4 = function(){
alert(a);
}
}
Celery.prototype = new Vegetable();
var stick = new Celery();
var polymorphed = stick.taste;
//alert(polymorphed);
//alert(stick.color);
//stick.fun1();
//stick.fun2();
//stick.fun3();
stick.fun4();
希望本文所述對大家JavaScript程序設計有所幫助。