• JavaScript继承


    JavaScript里常用的继承方式有两种:

    • 原型链继承(对象间的继承)
    • 类式继承(构造函数间的继承)

    由于 JavaScript 不像 java 那样是真正面向对象的语言,JavaScript 是基于对象的,它没有类的概念。所以,要想实现继承,可以用 JavaScript 的原型prototype机制或者用apply和call方法去实现。

    类式继承

    类式继承是在子类型构造函数的内部调用超类型的构造函数。
    严格的类式继承并不是很常见,一般都是组合着用:

    function Super(){
        this.colors=["red","blue"];
    }
    
    function Sub(){
        Super.call(this);
    }
    

    原型式继承是借助已有的对象创建新的对象,将子类的原型指向父类,就相当于加入了父类这条原型链。


    为了让子类继承父类的属性(也包括方法),首先需要定义一个构造函数。然后,将父类的新实例赋值给构造函数的原型,这就是原型链继承。代码如下:

    function Parent() {
      this.name = "Mike";
    }
    
    function Child() {
      this.age = 14;
    }
    
    //Child继承了Parent
    Child.prototype = new Parent();
    
    var child = new Child();
    console.log(child.age);    //14
    console.log(child.name);   // "Mike"
    
    

    在上面的例子中,我们创建了 2 个构造函数 ParentChild ,然后让 Child 继承 Parent,可以发现我们创建的 Child 的一个实例 instance 拥有了 Parent 的属性 name

    以上原型链继承还缺少一环,那就是Object,所有的构造函数都继承自Object,而继承Object是自动完成的。

    我们可以通过 instanceof操作符和 isPrototypeOf确认原型和实例的关系。

    只要用 instanceof 来测试实例与原型链中出现过的构造函数,结果就会返回 true

    console.log(instance instanceof Object);   //true
    console.log(instance instanceof Parent);   //true
    console.log(instance instanceof Child);    //true
    

    只要是原型链中出现过的原型,都可以说是该原型链派生的实例的原型,使用 isPrototypeOf 方法也会返回 true

    console.log(Object.prototype.isPrototypeOf(instance));   //true
    console.log(Parent.prototype.isPrototypeOf(instance));   //true
    console.log(Child.prototype.isPrototypeOf(instance));    //true
    

    在JavaScript中,被继承的函数称为超类型(父类,基类),继承的函数称为子类型(子类,派生类)。使用原型继承主要由两个问题:

    • 字面量重写原型会中断关系,包含引用类型的原型;
    • 子类型还无法给超类型传递参数。

    伪类解决引用共享和超类型无法传参的问题,我们可以采用“借用构造函数”技术。

    借用构造函数

    function Parent(age) {
      this.name = ["alpha", "beta", "gamma"];
      this.age = age;
    }
    
    function Child(age) {
      Parent.call(this, age);
    }
    
    var instance = new Child(11);
    console.log(instance.age);   // 11
    console.log(instance.name);  // ["alpha", "beta", "gamma"]
    instance.name.push("delta");
    console.log(instance.name);  // ["alpha", "beta", "gamma", "delta"]
    
    var another = new Child();
    console.log(another.age);    // undefiend
    console.log(another.name);   // ["alpha", "beta", "gamma"]
    

    借用构造函数虽然解决了传参包含引用类型值的原型的问题,但没有原型,但无法实现复用。
    所以我们需要原型链+借用构造函数的模式,这种模式称为组合继承。

    function Parent(age){
        this.name = ["alpha", "beta", "gamma"];
        this.age = age;
    }
    Parent.prototype.run = function () {
            return this.name  + " ' age is " + this.age;
    };
    
    function Child(age){
        Parent.call(this,age); //对象冒充,给超类型传参
    }
    Child.prototype = new Parent(); // 原型链继承
    var instance = new Child(20);  // 写new Parent(20)也行
    console.log(instance.run());  // alpha,beta,gamma ' age is 20
    

    组合式继承是比较常用的一种继承方法,其背后的思路是 : 使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。

    原型式继承

    function object(o) {
      function F(){}
      F.prototype = o;
      return new F();
    }
    

    在object内部,先创建一个临时性的构造函数,然后将传入的对象作为这个构造函数的原型,最后返回这个临时类型的一个新实例,从本质上讲, object() 对传入其中的对象执行了一次浅复制。如下例:

    var person = {
      name : "alpha",
      friends : ["beta", "gamma", "delta"]
    };
    
    var anotherPerson = Object(person);
    anotherPerson.name = "zeta";
    anotherPerson.friends.push("theta");
    //["beta", "gamma", "delta", "theta"]
    console.log(anotherPerson.friends); 
    
    var yetAnotherPerson = Object.create(person);
    yetAnotherPerson.name = "kappa";
    yetAnotherPerson.friends.push("lambda");
    //["beta", "gamma", "delta", "theta", "lambda"]
    console.log(yetAnotherPerson.friends);
    
    //["beta", "gamma", "delta", "theta", "lambda"]
    console.log(person.friends); 
    

    ECMAScript 新增了 Objectcreate()方法规范了原型式继承。


    寄生式继承
    这种继承方式是把原型式+工厂模式结合起来,目的是为了封装创建的过程。

    function create(o){
        var f= obj(o);
        f.run = function () {
            return this.arr;//同样,会共享引用
        };
        return f;
    }
    

    组合式继承的小问题
    组合式继承是JavaScript最常用的继承模式,但组合继承的超类型在使用过程中会被调用两次;一次是创建子类型的时候,另一次是在子类型构造函数的内部。

        function Parent(name){
            this.name = name;
            this.arr = ['哥哥','妹妹','父母'];
        }
    
        Parent.prototype.run = function () {
            return this.name;
        };
    
        function Child(name,age){
            Parent.call(this,age);//第二次调用
            this.age = age;
        }
    
        Child.prototype = new Parent();//第一次调用
    

    寄生组合式继承
    寄生组合继承,解决了两次调用的问题。

    function SuperType(name) {
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function() {
      console.log(this.name);
    };
    
    function SubType(name, age) {
      SuperType.call(this, name);
    
      this.age = age;
    }
    
    inheritPrototype(SubType, SuperType); //通过这里实现继承
    
    SubType.prototype.sayAge = function() {
      console.log(this.age);
    };
    

    call和apply
    全局函数apply和call可以用来改变函数中this的指向,如下:

     // 定义一个全局函数
        function foo() {
            console.log(this.fruit);
        }
    
        // 定义一个全局变量
        var fruit = "apple";
        // 自定义一个对象
        var pack = {
            fruit: "orange"
        };
    
        // 等价于window.foo();
        foo.apply(window);  // "apple",此时this等于window
        // 此时foo中的this === pack
        foo.apply(pack);    // "orange"
    
  • 相关阅读:
    ubuntu 14.4 apache2 django
    github上的版本和本地版本冲突的解决方法
    Javascript能做什么 不能做什么。
    django 取model字段的verbose_name值
    Django在admin模块中显示auto_now_add=True或auto_now=True的时间类型列
    合并多个python list以及合并多个 django QuerySet 的方法
    摘抄
    Python 字符串拼接
    学习HTTP
    Django 自定义模板标签和过滤器
  • 原文地址:https://www.cnblogs.com/zhoufulin/p/4979257.html
Copyright © 2020-2023  润新知