• JS 继承(类式 与 原型式)


    1.

    /* -- 类式继承 -- */
    //先声明一个超类

    function Person(name) {
    this.name = name;
    }
    //给这个超类的原型对象上添加方法 getName
    Person.prototype.getName = function() {
    return this.name;
    }
    //实例化这个超
    var a = new Person('Darren1')
    console.log(a.getName());//Darren1

    //再声明类

    function Programmer(name, sex) {
    //这个类中要调用超类Person的构造函数,并将参数name传给它
    Person.call(this, name);
    this.sex = sex;
    }
    //这个子类的原型对象等于超类的实例
    Programmer.prototype = new Person();
    // 因为子类的原型对象等于超类的实例,所以prototype.constructor这个方法也等于超类构造函数,你可以自己测试一下,如果没这一 步,console.log(Programmer.prototype.constructor这个是Person超类的引用,所以要从新赋值为自己本 身

    console.log(Programmer.prototype.constructor);
    /*function Person(name) {
    this.name = name;
    } */

    Programmer.prototype.constructor = Programmer;
    console.log(Programmer.prototype.constructor);

    /*function Programmer(name, sex) {
    Person.call(this, name);
    this.sex = sex;
    }
    */
    //子类本身添加了getSex 方法
    Programmer.prototype.getSex = function() {
    return this.sex;
    }
    //实例化这个子类
    var _m = new Programmer('Darren2', 'male');
    //自身的方法
    console.log(_m.getSex());//male
    //继承超类的方法
    console.log(_m.getName());//Darren2

    2.
    /* -- clone()方法封装的原型式继承 -- */
    //clone()函数用来创建新的类Person对象
    var clone = function(obj) {
    var _f = function() {};
    //这句是原型式继承最核心的地方,函数的原型对象为对象字面量
    _f.prototype = obj;
    return new _f;
    }
    //先声明一个对象字面量
    var Person = {
    name: 'Darren',
    getName: function() {
    return this.name;
    }
    }
    //不需要定义一个Person的子类,只要执行一次克隆即可
    var Programmer = clone(Person);
    //可以直接获得Person提供的默认值,也可以添加或者修改属性和方法
    alert(Programmer.getName())
    Programmer.name = 'Darren2'
    alert(Programmer.getName())

    //声明子类,执行一次克隆即可
    var Someone = clone(Programmer);

    4、继承的第四种方式:真正原型链方式,即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承
      function Person(){
      }
      Person.prototype.hello = "hello";
      Person.prototype.sayHello = function(){
        alert(this.hello);
      }
     
      function Child(){
      }
      Child.prototype = new Person();//这行的作用是:将Parent中将所有通过prototype追加的属性和方法都追加到Child,从而实现了继承
      Child.prototype.world = "world";
      Child.prototype.sayWorld = function(){
        alert(this.world);
      }
     
      var c = new Child();
      c.sayHello();
      c.sayWorld();

  • 相关阅读:
    [转帖]gesture recognition
    [转帖]了解AmbiLight知识
    [转帖]AVS音视频编解码技术了解
    [笔记]新概念英语听力
    ES 学习记录
    Spring Aop 错误之:No MethodInvocation found ... the ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that advices with order HIGHEST
    AOP无法切入同类调用方法解决办法
    多数据源 Spring 1.x 和 spring 2.x区别
    Intellij IDEA 在一个窗口添加多个项目并全部加入version control
    PageHelper 分页和排序之间的关系
  • 原文地址:https://www.cnblogs.com/koleyang/p/4871135.html
Copyright © 2020-2023  润新知