[size=large] [b]1.利用原型对象实现继承[/b][/size]
[b][size=large]2.通过构造函数实现继承[/size][/b]
[size=large][b]3.使用call方法和apply方法实现继承[/b][/size]
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//每个函数对象都具有prototype属性,这个属性保存了函数对象的原型对象的引用.而函数对象的所有属性和方法都"继承自这个原型对象".同样,构造函数也具有prototype属性.
function Person(name,sex) {
this.name=name;
this.sex=sex;
}
Person.prototype.sayHello=function (){
document.write("大家好,我的名字是"+this.name+".<br>");
}
//定义Student类,构造函数为空
function Student(){
}
Student.prototype=new Person("张三","男");
var student=new Student();
Student.prototype.grade="三年级";
Student.prototype.introduce=function(){
document.write("我是"+this.grade+"的学生............");
}
student.sayHello();
student.introduce();
//删除对象的属性和方法有两种方式:1是delete person.speak; 2是person.name="underfined;"
//-->
</script>
</body>
\</html>
[b][size=large]2.通过构造函数实现继承[/size][/b]
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//通过构造函数调用实现继承
//this关键字引用的是当前构造函数所创建的对象实例,当类B的构造函数作为类A的方法并在类A的构造函数中调用时,this引用的就是类A的构造函数所创建的实例,这样类A的实例就拥有了类B的属性和方法
function ClassA(name,age){
//将ClassB作为函数定义为ClassA的函数tempMthod
this.tempMethod=ClassB;
//调用tempMthod
this.tempMethod(name);
//删除tempMethod方法
delete this.tempMethod;
this.age=age;
this.sayHello=function(){
document.write("你好,我的名字叫"+this.name+",我今年"+this.age+"岁了!!!!<br>");
}
}
function ClassB(name){
this.name=name;
this.sayHello=function(){
document.write("我是不会告诉你我的名字叫"+this.name+"的!!!!!<br>");
}
}s
var classB =new ClassB("张三");
classB.sayHello();
var classA=new ClassA("李四",34);
classA.sayHello();
//删除对象的属性和方法有两种方式:1是delete person.speak; 2是person.name="underfined;"
//-->
</script>
</body>
</html>
[size=large][b]3.使用call方法和apply方法实现继承[/b][/size]
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//使用call方法和apply方法实现继承
//这两个方法可以将函数绑定到其他对象上执行
//可以将类B的构造函数绑定到类A的对象实例上执行,达到类A继承类B的目的
function Animal(color,age){
this.color=color;
this.age=age;
this.cry=function(){
document.write("Hi,我是"+this.color+"色的. 我今年"+this.age+"岁了!!<br>");
}
}
function Dog(color ,age){
Animal.call(this,color,age);
//使用call方法将Animal函数绑定到Dog实例上执行
}
function Cat(color ,age){
Animal.apply(this,[color,age]);
//使用apply方法将Animal函数绑定到Cat实例上执行
}
var animal=new Animal("绿",33);
animal.cry();
var dog=new Dog("黑",11);
dog.cry();
var cat =new Cat("白",4);
cat.cry();
//-->
</script>
</body>
\</html>