码迷,mamicode.com
首页 > Web开发 > 详细

js对象继承

时间:2017-05-28 15:30:56      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:问题   prototype   对象   func   people   for   alert   引用   div   

 一般继承是出现的问题

    function people(name,sex){
      this.name=name;
      this.sex=sex;
    }
    people.prototype.showname=function(){
      alert(this.name);
    }
    function student(name,sex,job){
      people.call(this,name,sex);
      this.job=job;
    }
    student.prototype = people.prototype;//对象赋给对象,就会出现对象的引用,如果子类原型添加一个方法,父类就会受影响
    var p1=new people(‘jack‘,32);
    var s1=new student(‘jenny‘,24,‘student‘);
    console.log(p1);
    console.log(s1);

拷贝继承

  function people(name,sex){
      this.name=name;
      this.sex=sex;
    }
    people.prototype.showname=function(){
      alert(this.name);
    }
    function student(name,sex,job){
      people.call(this,name,sex);//属性继承:调用父类的构造函数
      this.job=job;
    }

    extend(student.prototype,people.prototype);//拷贝继承,利用for in 实现方法的继承
    student.prototype.showjob=function(){
      alert();
    }
    function extend(obj1,obj2){
      for (var attr in obj2) {
        obj1[attr]=obj2[attr];
      }
    }
    var p1=new people(‘jack‘,32);
    var s1=new student(‘jenny‘,24,‘student‘);

    console.log(p1);
    console.log(s1);

 

 

 

js对象继承

标签:问题   prototype   对象   func   people   for   alert   引用   div   

原文地址:http://www.cnblogs.com/littlewriter/p/6915750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!