300
技術社區[雲棲]
javascript 對象繼承
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>4.2 對象繼承</title>
</head>
<body>
1.對象冒充:<br />
<script type="text/javascript">
//實例1:簡單繼承
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () { alert("ClassA.sayColor:" + this.color); }
}
function ClassB(sColor, name) {
this.newMethod = ClassA; //傳遞ClassA引用
this.newMethod(sColor); //調用ClassA對象,繼承ClassA的方法
delete this.newMethod; //刪除對ClassA的引用
this.name = name;
this.sayName = function () { alert("ClassB.sayName:" + this.name); }
}
var a = new ClassA("red");
var b = new ClassB("green", "hello");
a.sayColor();
b.sayColor();
b.sayName();
//實例2:多繼承
//這裏存在一個弊端,如果ClassA和ClassB具有相同的屬性或方法,那麼後者將具有更高的優先級。
function ClassC(sColor, name, age) {
this.newMethod = ClassA; //傳遞ClassA引用
this.newMethod(sColor); //調用ClassA對象,繼承ClassA的方法
delete this.newMethod; //刪除對ClassA的引用
this.newMethod = ClassB; //傳遞ClassB引用
this.newMethod(sColor, name); //調用ClassB對象,繼承ClassB的方法
delete this.newMethod; //刪除對ClassB的引用
this.age = age;
this.sayAge = function () { alert("ClassC.sayAge:" + this.age); }
}
var c = new ClassC("green", "hello", 25);
c.sayColor();
c.sayName();
c.sayAge();
</script>
2.call()方法:<br />
<script type="text/javascript">
//實例3:call()方法
function ClassD(sColor, name) {
ClassA.call(this, sColor); //類似C#裏的擴展方法
this.name = name;
this.sayName = function () { alert("ClassD.sayName:" + this.name); }
}
var d = new ClassD("blue", "hello");
d.sayColor();
d.sayName();
</script>
3.apply()方法:<br />
<script type="text/javascript">
//實例4:apply()方法
function ClassE(sColor, name) {
ClassA.apply(this, arguments); //用數組打包參數,也可以是ClassA.apply(this, new Array(sColor));
this.name = name;
this.sayName = function () { alert("ClassE.sayName:" + this.name); }
}
var e = new ClassD("red", "hello");
e.sayColor();
e.sayName();
</script>
4.原型鏈方式:<br />
<script type="text/javascript">
//實例5:原型鏈方式
function ClassF(sColr) {
this.color = sColor;
}
ClassF.prototype.sayColor = function () { alert("ClassF.prototype.sayColor:" + this.sColor); }
function ClassG(sColor, name) {
ClassA.call(this, sColor); //屬性:用對象冒充繼承ClassF的sColor屬性
this.name = name;
}
ClassG.prototype = new ClassF(); //方法:用原型鏈方式繼承ClassF類的方法
ClassG.prototype.sayName = function () { alert("ClassG.prototype.sayName:" + this.name); }
var g = new ClassD("red", "hello");
g.sayColor();
g.sayName();
</script>
</body>
</html>
最後更新:2017-04-03 18:51:44