zoukankan      html  css  js  c++  java
  • js对象继承

     一般继承时出现的问题

        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);

    拷贝继承:通用型的,有new或无new的时候都可以

      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);

     类式继承:带new构造函数

    function Aaa(){
        this.name=[2,3,4];
    }
    Aaa.prototype.showname=function(){
        alert(this.name);
    }
    function Bbb(){
        Aaa.call(this);
    }
    var F= function(){};
    F.prototype=Aaa.prototype;
    Bbb.prototype=new F();
    Bbb.prototype.constructor=Bbb;
    var b1=new Bbb();
    b1.name.push(5);
    var b2=new Bbb();
    alert(b2.showname);

    原型继承:无new的对象

    var a = {name: '小明'};
    var b = clone(a);
    b.name='小青'; alert(a.name);
    function clone(obj){ var F =function(){}; F.prototype=obj; return new F(); }
     
  • 相关阅读:
    Logstash 安装并把mysql数据同步到elasticsearch
    springboot 集成elasticsearch
    centos7 搭建Elasticsearch集群
    centos7 elasticsearch 安装
    elasticsearch 深度分页以及scroll 滚动搜索
    elasticsearch DSL常用查询总结
    elasticsearch ik分词器自定义词库
    elasticsearch 安装IK中文分词器
    elasticsearch 分词与内置分词器
    elasticsearch 文档乐观锁控制 if_seq_no与if_primary_term
  • 原文地址:https://www.cnblogs.com/littlewriter/p/6915750.html
Copyright © 2011-2022 走看看