DIV CSS 佈局教程網

面向對象繼承實例:A 如何繼承 B(自寫)
編輯:關於JavaScript     

複製程式碼 程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>面向對象繼承實例</title>
<script type="text/javascript">
window.onload = function(){
function parent(age,name){
this.age = age;
this.name = name;
}
parent.prototype.show = function(){
alert('父級方法');
}
function child(age,name,job){
parent.apply(this,arguments);
this.job = job;
}
(function(){
for(var i in parent.prototype){
child.prototype[i]=parent.prototype[i]
}
})();
var b = new parent(14,'俠客行');
var a = new child(15,'狼俠','俠客');
a.show();
}
</script>
</head>
<body>
<h1>面向對象繼承實例</h1>
<p>經常看到面試題有關繼承問題 a 如何繼承 b,決定寫一下,其實繼承就是繼承父級的屬性和方法</p>
</body>
</html>

這個範例示範了最基礎的繼承寫法:子函式 child 透過 parent.apply(this, arguments) 繼承父級的實例屬性(age、name),再用一個迴圈把 parent.prototype 上的方法逐一複製到 child.prototype,於是子物件 a 就能呼叫父級的 show 方法,達到屬性與方法雙重繼承的效果。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved