javaScript中并不存在继承的感念..但是我们可以根据javaScript的原型进行模拟JavaScript的"继承":
1.写两个函数对象,将其中的一个函数赋值给另一个函数对象的原型:
<script type="text/javascript">
function A(){
this.a = "a";
this.sayA = function(){
alert("this is a.");
}
}
var a = new A();
function B(){
this.b = "b";
this.sayB = function(){
alert("this is b.");
}
}
B.prototype = a;
//测试:函数对象B就"继承"了函数对象A
var b = new B();
alert(b.b);
b.sayB();
alert(b.a);
b.sayA();
</script>
运行结果:
2.只继承于原型(定义A的函数对象,定义A函数对象的原型.定义B函数对象,把A对象的函数原型赋值给B的原型)
function A(){}
A.prototype = {
a : "a",
sayA : function(){
alert("this is a.")
}
}
function B(){
this.b = "b";
this.sayB = function(){
alert("this is b.");
}
}
B.prototype = A.prototype;
var b = new B();
alert(b.b);
b.sayB();
alert(b.a);
b.sayA();
3.实现多继承
<script type="text/javascript">
function A(){}
A.prototype = {
a : "a",
sayA : function(){
alert("this is a.")
}
}
function B(){}
B.prototype = A.prototype;
B.prototype.b = "b";
B.prototype.sayB = function(){
alert("this is b.")
}
var b = new B();
alert(b.a);
b.sayA();
alert(b.b);
b.sayB();
</script>
* 分析得出这句话出问题了
* * 因为B.prototype多次调用
* * 出现的顺序有关系?谁先定义,谁被覆盖
* * 原型定义属性和方法的形式有关系?没有关系
* 条件:
* * 先实现函数对象B"继承"函数对象A的内容
* * 再利用原型为函数对象B增加属性和方法(分散形式)