javascript繼承實現

從java繼承的角度來講,子類extends父類之後,子類應該具有父類的public,protected訪問權限限制的屬性和方法.那在js中如何實現呢?

請看下面的例子:

<html>
<body>
<script type="text/javascript">
function Parent(name){
this.name = name || "default";
this.age=24;// Parent 獨有的屬性
this.wife = function(){ // Parent獨有的屬性
return "Parent's wife is my mother";
}
}
function Child(name,sex){
this.self=Parent; // 將Parent的引用賦值給當前對象本身
this.self(name); // 初始化Parent對象
delete this.self; // 刪除當前對象的self
this.sex = sex || "M";
}
function test(){
var child = new Child("okgogogo","M");
alert(child.name);
alert(child.sex);
alert(child.age); // 此處結果爲24,那麼則說明Child繼承了Parent
alert(child.wife()); // 此處結果爲 :Parent's wife is my mother(額,其實這是一句P話)
}
</script>
<input type="button" value="click me" onclick="test()"></input>
</body>
</html>

發佈了61 篇原創文章 · 獲贊 87 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章