一,js中对象继承
js中有三种继承方式
1.js原型(prototype)实现继承
代码如下:
<SPAN style="BACKGROUND-COLOR: #ffffff"><SPAN style="FONT-SIZE: 18px"><html>
<body>
<script type="text/javascript">
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayHello=function(){
alert("使用原型得到Name:"+this.name);
}
var per=new Person("马小倩",21);
per.sayHello(); //输出:使用原型得到Name:马小倩
function Student(){}
Student.prototype=new Person("洪如彤",21);
var stu=new Student();
Student.prototype.grade=5;
Student.prototype.intr=function(){
alert(this.grade);
}
stu.sayHello();//输出:使用原型得到Name:洪如彤
stu.intr();//输出:5
</script>
</body>
</html></SPAN></SPAN>
2.构造函数实现继承
代码如下:
<SPAN style="FONT-SIZE: 18px"><html>
<body>
<script type="text/javascript">
function Parent(name){
this.name=name;
this.sayParent=function(){
alert("Parent:"+this.name);
}
}
function Child(name,age){
this.tempMethod=Parent;
this.tempMethod(name);
this.age=age;
this.sayChild=function(){
alert("Child:"+this.name+"age:"+this.age);
}
}
var parent=new Parent("江剑臣");
parent.sayParent(); //输出:“Parent:江剑臣”
var child=new Child("李鸣",24); //输出:“Child:李鸣 age:24”
child.sayChild();
</script>
</body>
</html></SPAN>
新闻热点
疑难解答
图片精选