<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>javascriptInherited.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<script type="text/javascript">
//Javascript对象的继承
//对象冒充
function Car(sColor){
this.sColor = sColor;
this.showColor = function(){
alert(this.sColor);
};
}
//inherit Car
function MyCar(sColor,sMoney){
this.newMethods = Car;
this.newMethods(sColor);
//删除的目地是为了防止重写父类的方法和属性
//但是我试了一下,不删除也基本上可以用,
//也没有发现什么问题
delete this.newMethods;
this.sMoney = sMoney;
this.showMoney = function(){
alert(sMoney);
};
}
//混合方式的继承call(),apply()
function ClassA(sColor){
this.sColor = sColor;
}
ClassA.prototype.showColor = function(){
alert(this.sColor);
};
//inherit
function ClassB(sColor,fMoney){
//三种继承的方法,第三种是传所有的参数arguments
ClassA.call(this,sColor);
//ClassA.apply(this,new Array(sColor));
//ClassA.apply(this,arguments);
this.fMoney = fMoney;
}
ClassB.prototype = new ClassA();
ClassB.prototype.showMoney = function(){
alert(this.sColor+" "+this.fMoney);
};
//动态原型的继承方式
function ClassF(sColor){
this.sColor = sColor;
if(typeof ClassF._init == "undefined"){
ClassF.prototype.showColor = function(){
alert(this.sColor);
};
ClassF._init = true;
}
}
//Inherit ClassF
function ClassS(sColor,iMoney){
ClassF.apply(this,arguments);
this.iMoney = iMoney;
if(typeof ClassS._inits == "undefined"){
ClassS.prototype.showMoney = function(){
alert(this.sColor+" "+this.iMoney);
};
ClassS._inits = true;
}
}
//好像必须得写成这样,不然的话就会报错
ClassS.prototype = new ClassF();
window.onload = function(){
//对象冒充
//var mycar = new MyCar("red",50);
//mycar.showMoney();
//mycar.showColor();
//var myclass = new ClassB("red",20);
//myclass.showColor();
//myclass.showMoney();
var autoClass = new ClassS("blue",3000);
autoClass.showMoney();
autoClass.showColor();
}
</script>
<body>
</body>
</html>
Javascript对象的继承
最新推荐文章于 2021-09-22 17:53:27 发布