javascriptの中で相続を実現するいくつかの方法……
4489 ワード
1.原型オブジェクトを利用して継承を実現する
<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>
2.構造関数による継承 <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>
3.call方法とappy方法で継承を実現する <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>