博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ES6 class 技术点拾遗
阅读量:7037 次
发布时间:2019-06-28

本文共 1357 字,大约阅读时间需要 4 分钟。

语法

 

  • 方法不需要加function,方法之间不需要加分号
class Point {    constructor(x, y) {        this.x = x;        this.y = y;    }    toString() {        return '(' + this.x + ', ' + this.y + ')';    }    getX() {        return this.x;    }}

类的prototype

类的方法都定义在prototype上,但是是不可以枚举的。

class Point {    constructor(x, y) {        this.x = x;        this.y = y;    }    toString() {        return '(' + this.x + ', ' + this.y + ')';    }    getX() {        return this.x;    }}Point.prototype.aa = function (){}console.log(Object.keys(Point.prototype))//输出['aa']

 

静态方法

  • 静态方法的this指向类,而不是示例
  • 静态方法可以和实力方法重名
  • 父类的静态方法可可以被子类继承
  • class内部只有静态方法,而没有静态属性
class Foo {  static bar () {    this.baz();  }  static baz () {    console.log('hello');  }  baz () {    console.log('world');  }}Foo.bar() // hello// 以下两种写法都无效class Foo {  // 写法一  prop: 2  // 写法二  static prop: 2}Foo.prop // undefined

继承

  • 使用extends关键字实现继承
  • 使用super调用父类的构造函数
  • super函数必须在子类的构造函数中调用,否则会报错。
  • super函数位于子类构造函数的第一行!因为子类的this必须先通过父类的构造函数完成构造。不调用super方法,子类就得不到this对象。也就是说子类若是有构造函数的话,构造函数的第一行必须是super。
  • super当做函数使用时,即super(),只能用在子类的构造函数中。当做对象使用时,即super.方法(),指向父类的原型对象(在静态方法中指向父类),此时注意是调用父类原型上的方法(或者父类的静态方法),而不是实例方法;同时this指向子类的实例。
class ColorPoint extends Point {  constructor(x, y, color) {    super(x, y); // 调用父类的constructor(x, y)    this.color = color;  }  toString() {    return this.color + ' ' + super.toString(); // 调用父类的toString()  }}

转载地址:http://mcnal.baihongyu.com/

你可能感兴趣的文章
Django框架---model模型基础
查看>>
ubuntu上安装virtualbox,虚拟winxp系统
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
门禁的实际应用
查看>>
UIView animateWithDuration 使用详解
查看>>
解决“无法在windows资源管理器中打开ftp站点”问题
查看>>
服务器架构系统软件简单分类
查看>>
我的友情链接
查看>>
完全备份、差异备份以及增量备份的区别
查看>>
关于unix、dos文件格式^M处理方法整理
查看>>
2.2Python数据处理篇之---math模块的数学函数
查看>>
Data Augmentation
查看>>
C#.NET 剪切板复制粘贴泛型的例子代码参考 Clipboard Copy Paste List
查看>>
我的友情链接
查看>>
JAVA经典面试题集锦(转)
查看>>
rsync+inotify应用案例
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
nginx 访问日志分析
查看>>