javascript中实现继承的几个方法........

本文介绍了JavaScript中三种实现继承的方法:利用原型对象实现继承、通过构造函数实现继承以及使用call和apply方法实现继承。通过具体代码示例展示了每种方法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=large] [b]1.利用原型对象实现继承[/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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值