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(); }
     
  • 相关阅读:
    spring整合websocket通信
    Log4j学习
    Elasticsearch学习之ES节点类型以及各种节点的分工
    Elasticsearch 学习之提升性能小贴士
    Python奇技淫巧
    汉语拼音转换工具(Python 版)
    根据数据库的表结构的类型返回其对应的简写类型
    python的动态加载机制??
    计算二进制中的字符串的长度
    一个erlang游戏服务端
  • 原文地址:https://www.cnblogs.com/littlewriter/p/6915750.html
Copyright © 2011-2022 走看看