• es6中的class的使用


    ---恢复内容开始---

    es5中生成实例对象的传统方法是通过构造函数:

    function Point(x,y){
            this.x = x;
            this.y = y;
        }
        Point.prototype.toString = function(){
    
            return '(' + this.x + ', ' + this.y + ')';
        }
    var p= new Point(2,3);
    console.log(p.toString())

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

    class Point{
    	constructor(x,y){
    	  this.x = x;
    	  this.y = x;
    	}
    	  toString(){
    		return '(' + this.x + ', ' + this.y + ')';
    	  }
    }
    var p= new Point(2,3);
    console.log(p.toString())
    

      浏览器的执行结果

    上面代码定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。

    class Point {
      // ...
    }
    
    typeof Point // "function"
    Point === Point.prototype.constructor // true

    类的数据类型就是函数,类本身就指向构造函数。
    constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
    class Point {
    }
    
    // 等同于
    class Point {
      constructor() {}
    }
    

     如果忘记加上new,像函数那样调用Class,将会报错

    class Point {
      // ...
    }
    
    // 报错
    var point = Point(2, 3);
    
    // 正确
    var point = new Point(2, 3);
    

     super可以继承类

    class Animal{
    	constructor(name){
    		this.name = name;
    	}
    	getName() {
    		return this.name
    	}
    }
    	let animal = new Animal('animal');
    	console.log(animal.getName());
    	class Cat extends Animal{
    		constructor() {
    			super()
    			this.name = 'cat';
    		}
    	}
    	let cat = new Cat();
    	console.log(cat.getName())
    

      运行结果:

    使用super()注意

    在构造函数中访问this之前一定调用super(),它负责初始化this,如果在调用super()之前之前尝试访问this会导致程序出错

    如果不想调用super(),唯一的方法就是让类的构造函数返回一个对象

    父类的静态方法可以被子类继承:

    class Foo {
      static classMethod() {
        return 'hello';
      }
    }
    
    class Bar extends Foo {
    }
    
    Bar.classMethod() // 'hello'
    

      可计算成员名称:类和对象字面量有很多相似之处,类方法和访问器属性也支持使用可计算名称,用方括号包裹一个表达式可使用计算名称:

    let methodName = "sayName";
    	class PersonClass {
    		constructor(name){
    			this.name = name;
    		}
    		[methodName](){
    			console.log(this.name)
    		}
    	}
    	let me = new PersonClass("ninaclass");
    	me.sayName();//ninaclass
    

      

    ---恢复内容结束---

  • 相关阅读:
    没有功能需求文档就拒绝开发吗?
    用Spring cloud Stream来开发基于MQ消息驱动的微服务
    在Linux上讲Java命令行的作为服务运行
    EF提供的三种查询方式
    C#中sealed关键字
    winform Chart控件 获取鼠标处坐标值方法
    Linq to Entity中连接两个数据库时要注意的问题
    linq中查询列表的使用及iqueryable和list集合之间的转换
    C语言关键字register、extern、static
    DllImport的具体用法
  • 原文地址:https://www.cnblogs.com/smdb/p/10221791.html
Copyright © 2020-2023  润新知