JavaScript继承与原型链

  1. 继承和原型链是什么?
    1.1 在继承中,子类继承父类的特征和行为,使得子类对象具有父类的实例域和方法。这意味着子类可以使用父类的方法和属性,使用继承的目的是为了更好设置实例的公共属性和方法,如下例子:

      // 以类的形式说明继承,直观一点
      // 父类
      class Animal {
          
          
        constructor() {
          
          
          this.area = '广东'
        }
        helloMethod () {
          
          
          return `它是${
            
            this.area}的动物`
        }
      }
      // 子类,子类继承了父类的属性和方法
      class Dog extends Animal {
          
          
        constructor(name) {
          
          
          super() // 调用父类的构造函数
          this.name = name
        }
        introduce () {
          
          
          return `${
            
            this.name}是一只狗`
        }
      }
      const dog1 = new Dog('咕咕')
      console.log(dog1.introduce()); // 咕咕是一只狗--introduce是自身实例的方法
      console.log(dog1.name); //  咕咕--name是自身实例的属性
      console.log(dog1.area); //  广东--area是继承了父类的属性
      console.log(dog1.helloMethod()); //  它是广东的动物--helloMethod是继承了父类的方法
    

    1.2 原型链:是javascript中实现对象间继承和代码重用的一种机制。
    JavaScript 只有一种结构:对象(广义的对象,不单指object)。每个对象都有一个私有属性指向另一个名为原型(prototype)的对象。原型对象也有一个自己的原型,层层向上直到一个对象的原型为 null。根据定义,null 没有原型,并作为这个原型链(prototype chain)中的最后一个环节。

    当你试图访问一个对象的属性时,如果在该对象本身中找不到该属性,就会在其原型中搜索该属性,如果仍然找不到,那么就会搜索原型的原型,以此类推,直到找到一个名字匹配的属性或到达原型链的末尾(即原型为null的对象)。

  2. 使用不同的方法来创建对象和改变原型链
    2.1 使用语法结构创建对象

    const o = {
          
           a: 1 };
    // 新创建的对象 o 以 Object.prototype 作为它的 [[Prototype]]
    // Object.prototype 的原型为 null。
    // 其原型链如下所示:
    // o ---> Object.prototype ---> null
    
    const b = ["yo", "whadup", "?"];
    // 数组继承了 Array.prototype(具有 indexOf、forEach 等方法)
    // 其原型链如下所示:
    // b ---> Array.prototype ---> Object.prototype ---> null
    
    function f() {
          
          
      return 2;
    }
    // 函数继承了 Function.prototype(具有 call、bind 等方法)
    // 其原型链如下所示:
    // f ---> Function.prototype ---> Object.prototype ---> null
    
    const p = {
          
           b: 2, __proto__: o };
    // 可以通过 __proto__ 字面量属性将新创建对象的
    // [[Prototype]] 指向另一个对象。
    // (不要与 Object.prototype.__proto__ 访问器混淆,Object.prototype.__proto__添加原型链方法已经不推荐使用)
    // 其原型链如下所示:
    // p ---> o ---> Object.prototype ---> null
    
    

    2.2 使用构造函数

    function Family (name) {
          
          
      this.nameOfFamily = `${
            
            name}的家庭成员`
      this.persons = []
    }
    // 在Family原型链上添加addPerson方法,供后续创建的实例访问此公共的方法
    Family.prototype.addPerson = function (name) {
          
          
      this.persons.push(name)
    }
    
    const family = new Family('李四')
      family.addPerson('李四')
      family.addPerson('李四的妹妹')
      console.log(family.nameOfFamily); // 李四的家庭成员
      console.log(family.persons); // ['李四', '李四的妹妹']
      
    const family1 = new Family('王五')
      family1.addPerson('王五')
      family1.addPerson('王五的弟弟')
      console.log(family1.nameOfFamily); // 王五的家庭成员
      console.log(family1.persons); // ['王五', '王五的弟弟']
    

    2.3 使用 Object.create()

    const a = {
          
           a: 1 };
    // a ---> Object.prototype ---> null
    
    const b = Object.create(a);
    // b ---> a ---> Object.prototype ---> null
    console.log(b.a); // 1 (inherited)
    
    const c = Object.create(b);
    // c ---> b ---> a ---> Object.prototype ---> null
    
    const d = Object.create(null);
    // d ---> null(d 是一个直接以 null 为原型的对象)
    console.log(d.hasOwnProperty);
    // undefined,因为 d 没有继承 Object.prototype
    
    

    2.4 使用类class

      class Polygon {
          
          
        constructor(height, width) {
          
          
          this.height = height;
          this.width = width;
        }
      }
    
      class Square extends Polygon {
          
          
        constructor(sideLength) {
          
          
          super(sideLength, sideLength);
        }
    
        get area() {
          
          
          return this.height * this.width;
        }
    
        set sideLength(newLength) {
          
          
          this.height = newLength;
          this.width = newLength;
        }
      }
    
      const square = new Square(2);
      // square ---> Square.prototype ---> Polygon.prototype ---> Object.prototype ---> null
      console.log(square.area); // 4
      square.sideLength = 3
      console.log(square.area); // 9
    

    2.5 使用 Object.setPrototypeOf()

    const obj = {
          
           a: 1 };
    const anotherObj = {
          
           b: 2 };
    Object.setPrototypeOf(obj, anotherObj);
    // obj ---> anotherObj ---> Object.prototype ---> null
    
    

    2.6 使用 proto 访问器(性能不佳且已被弃用)

      const obj = {
          
          };
      // 请不要使用该方法:仅作为示例。
      obj.__proto__ = {
          
           barProp: "bar val" };
      obj.__proto__.__proto__ = {
          
           fooProp: "foo val" };
      console.log(obj.fooProp); // foo val
      console.log(obj.barProp); // bar val
    

除非是为了与新的 JavaScript 特性兼容,否则永远不应扩展原生原型。

参考mdn阮一峰日志

猜你喜欢

转载自blog.csdn.net/qq_42832446/article/details/135823660