zoukankan      html  css  js  c++  java
  • Nodejs与ES6系列4:ES6中的类

    ES6中的类

    4.1、class基本语法

    在之前的javascript语法中是不存在class这样的概念,如果要通过构造函数生成一个新对象代码

    function Shape(width,height){
      this.width = width;
      this.height = height;
    }
    
    Point.prototype.toString = function () {
      return '(' + this.width + ', ' + this.height + ')';
    }
    

    ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用ES6的“类”改写,就是下面这样。

    //定义类
    class Shape {
    
      constructor(width, height) {
        this.height = height;
        this.width = width;
      }
    
      toString() {
        return '(' + this.width + ', ' + this.height + ')';
      }
    
    }
    

    通过class定义类名,constructor关键字定义构造函数。

    4.2、继承与多态

    继承与多态是面向对象最重要的两个特性,通过继承可以实现代码的重构,在之前的javascript中继承需要通过原型链来实现,而在ES6中可以通过extends关键字直观的实现继承。首先定义基类Shape,定义子类Rect集成与基类并重写方法toArea实现多态。

    'use strict'
    class Shape {
        constructor(width,height){
            this.width=width;
            this.height=height;
        }
        /***
         * 获取面积
         * @returns {number}
         */
        toArea(){
            return this.width*this.height
        }
    }
    module.exports = Shape;
    
    'use strict'
    var Shape = require('./Shape');
    class Rect extends Shape {
        constructor(width, height) {
            super(width, height);
        }
        toArea() {
            return this.width*this.height*2
        }
    }
    module .exports = Rect;
    

    子类Rect集成与基类Shape,拥有了基类的方法toArea,和属性width与height,而子类通过相同的方法名重写了方法toArea。

    var sharp = new Sharp(1,2);
    var rect = new Rect(1,2);
    console.log(sharp.toArea());
    console.log(rect.toArea());
    ====
    2
    4
    

    4.3、类的静态方法

    ES6中的类提供静态方法,静态方法只能在类成员下调用,如果类实例化后再调用会抛出异常。同样的基类定义的静态方法能被子类所继承。静态方法通过static关键字定义。

    'use strict'
    class Shape {
        constructor(width,height){
            this.width=width;
            this.height=height;
        }
        /***
         * 获取面积
         * @returns {number}
         */
        toArea(){
            return this.width*this.height
        }
        /**
         * 静态方法
         * @returns {string}
         */
        static toName(){
            return 'shape'
        }
    }
    module.exports = Shape;
    
    console.log(Rect.toName());
    ===
    shape
    

    值得注意的是在ES6的类中并没有静态属性的概念。静态属性可以通过Shape.name这样来定义。

  • 相关阅读:
    jsp页面的基本语法
    servlet转发与重定向
    servlet配置及其生命周期
    Java--普通代码块静态代码块执行顺序
    Maven简述
    JDBCTemplate
    AOP--Aspect Oriented Programming
    SpringMVC---简单练手项目
    SpringMVC---进阶篇
    SpringMVC---基础篇(2)
  • 原文地址:https://www.cnblogs.com/vipyoumay/p/5598017.html
Copyright © 2011-2022 走看看