`
wohenni0931
  • 浏览: 423 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

JS中的对象继承

阅读更多
1、原型继承(prototype)
<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("洪如彤");  
   var stu=new Student();
   alert(stu.name);//洪如彤 
   alert(stu.age);//undefined,因为new的时候只传了name
   Student.prototype.grade=5;
   Student.prototype.intr=function(){
      alert(this.grade);
   } 
   stu.intr();//5  
</script> 


2、call,apply继承
<script type="text/javascript">
function Person(name,age,love){
   this.name = name;
   this.age = age;
   this.love = love;
   this.say = function say(){
      alert("姓名:"+name+",年龄:"+age+",伴侣:"+love);
   }
}

function student(name,age){
   Person.call(this,name,age);
}

function teacher(name,love){
   Person.apply(this,[name,love]);
// Person.apply(this,arguments);//跟上一句一样效果
}

//call与aplly的区别:call的参数是列表;apply参数是数组(arguments也可以)

var per = new Person("小明",25,"小红");
per.say();//姓名:小明 ,年龄:25,伴侣:小红
var stu = new student("李磊",18);
stu.say();//姓名:李磊 ,年龄:18,伴侣:undefined
var tea = new teacher("高老师","伴侣名字");
tea.say();//姓名:高老师 ,年龄:伴侣名字,伴侣:undefined。说明参数只和位置有关
</script>


3、构造函数继承
<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("小明",25); 
child.sayChild();//Child:小明,age:25
child.sayParent();//Parent:小明
</script>




有些代码摘自网上,只做部分修改。第一次写文章是一个好的开端,如果有错或建议,请留言
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics