zoukankan      html  css  js  c++  java
  • 使用 Object.create 创建对象,super 关键字,class 关键字

    ECMAScript 5 中引入了一个新方法:Object.create()。可以调用这个方法来创建一个新对象。新对象的原型就是调用 create 方法时传入的第一个参数:

    var a = {a: 1}; 
    // a ---> Object.prototype ---> null
    
    var b = Object.create(a);
    // b ---> a ---> Object.prototype ---> null
    console.log(b.a); // 1 (继承而来)
    
    var c = Object.create(b);
    // c ---> b ---> a ---> Object.prototype ---> null
    
    var d = Object.create(null);
    // d ---> null
    console.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype
    

    使用 class 关键字

    ECMAScript6 引入了一套新的关键字用来实现 class。使用基于类语言的开发人员会对这些结构感到熟悉,但它们是不一样的。 JavaScript 仍然是基于原型的。这些新的关键字包括 classconstructorstaticextends, 和 super.

    "use strict";
    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;
      }
    }
    
    var square = new Square(2);
    

    super 关键字用于访问父对象上的函数。

    class Polygon {
      constructor(height, width) {
        this.name = 'Polygon';
        this.height = height;
        this.width = width;
      }
      sayName() {
        console.log('Hi, I am a ', this.name + '.');
      }
    }
    
    class Square extends Polygon {
      constructor(length) {
        this.height; // 这里会报错, 必须要先调用 super!
        
        // 这里我们调用父类的构造方法并传入 length
        // 作为 Polygon's 的 width 和 height
        super(length, length);
        
        // Note: 在派生的类中, super() 必须在 'this' 之前调用
        // 如果漏掉,则会造成引用错误。
        this.name = 'Square';
      }
    
      get area() {
        return this.height * this.width;
      }
    
      set area(value) {
        this.area = value;
      } 
    }
    

      

    调用父类上的静态方法

    你也可以用 super 调用父类的 静态方法

    class Human {
      constructor() {}
      static ping() {
        return 'ping';
      }
    }
    
    class Computer extends Human {
      constructor() {}
      static pingpong() {
        return super.ping() + ' pong';
      }
    }
    Computer.pingpong(); // 'ping pong'
    

    在对象字面量中使用 super.prop

    var obj1 = {
      method1() {
        console.log("method 1");
      }
    }
    
    var obj2 = {
      method2() {
       super.method1();
      }
    }
    
    Object.setPrototypeOf(obj2, obj1);
    obj2.method2(); // logs "method 1"
    

      

     

     

  • 相关阅读:
    torch 入门
    编译CDH Spark源代码
    Marsedit 破解版下载(3.5.6)
    程序员必备:技术面试准备手册
    360私有化详细资料曝光:抵押总部大楼(转)
    底层软件工程师的一次冒险经历
    这十种算法撑起了整个世界
    秒杀系统架构分析与实战(深度学习资料)
    北京程序员 VS 硅谷程序员(转)
    Timestamp 使用
  • 原文地址:https://www.cnblogs.com/laneyfu/p/6082782.html
Copyright © 2011-2022 走看看