博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
es6从零学习(三):Class的基本用法
阅读量:7123 次
发布时间:2019-06-28

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

es6从零学习(三):Class的基本用法

一:定义一个类

//定义类class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}

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

Point类除了构造方法,还定义了一个toString方法。注意,定义“类”的方法的时候,前面不需要加上function这个关键字

注意:类里面不可以添加属性,只能用object.assgin添加

 

二:使用

使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。

class Bar {  doStuff() {    console.log('stuff');  }}var b = new Bar();b.doStuff() // "stuff"

  

三:类的prototype属性

1、类的所有方法都定义在类的prototype属性上面。

class Point {  constructor() {    // ...  }  toString() {    // ...  }  toValue() {    // ...  }}// 等同于Point.prototype = {  constructor() {},  toString() {},  toValue() {},};

2、在类的实例上面调用方法,其实就是调用原型上的方法

class B {}let b = new B();b.constructor === B.prototype.constructor // true

3、类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法和属性值。

class Point {  constructor(){    // ...  }}Object.assign(Point.prototype, {  toString(){},  toValue(){},   aa:123});

注意:这里直接用Object.assign方法对Point进行操作会报错。

 

4、类的方法名,可以采用表达式。

let methodName = 'getArea';class Square {  constructor(length) {    // ...  }  [methodName]() {    // ...  }}

注意:这里不可以对属性的名字用表达式,会报错。

5、类必须使用new调用,否则会报错

class Foo {  constructor() {    return Object.create(null);  }}Foo()// TypeError: Class constructor Foo cannot be invoked without 'new'

  

四:类的constructor方法

1、constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加

class Point {}// 等同于class Point {  constructor() {}}

  

五:类的实例对象

1、实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。

//定义类class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}var point = new Point(2, 3);point.toString() // (2, 3)point.hasOwnProperty('x') // truepoint.hasOwnProperty('y') // truepoint.hasOwnProperty('toString') // falsepoint.__proto__.hasOwnProperty('toString') // truePoint.property.hasOwnProperty('toString') // true

上面代码中,xy都是实例对象point自身的属性(因为定义在this变量上),所以hasOwnProperty方法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法返回false。这些都与 ES5 的行为保持一致。

2、类的所有实例共享一个原型对象。

var p1 = new Point(2,3);var p2 = new Point(3,2);p1.__proto__ === p2.__proto__//true

上面代码中,p1p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

注意:这里的__proto__是两段下划线

3、可以通过实例的__proto__属性为“类”添加方法。

var p1 = new Point(2,3);var p2 = new Point(3,2);p1.__proto__.printName = function () { return 'Oops' };p1.printName() // "Oops"p2.printName() // "Oops"var p3 = new Point(4,2);p3.printName() // "Oops"

使用实例的__proto__属性改写原型,必须相当谨慎,不推荐使用,因为这会改变“类”的原始定义,影响到所有实例。

4、不存在变量提升:类不存在变量提升(hoist)

new Foo(); // ReferenceErrorclass Foo {}

这种规定的原因与继承有关,必须保证子类在父类之后定义。

 

六:Class表达式

1、采用 Class 表达式,可以写出立即执行的 Class。

let person = new class {  constructor(name) {    this.name = name;  }  sayName() {    console.log(this.name);  }}('张三');person.sayName(); // "张三"

上面代码中,person是一个立即执行的类的实例

 

七:Class 的静态方法

1、静态方法:如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {  static classMethod() {    return 'hello';  }}Foo.classMethod() // 'hello'var foo = new Foo();foo.classMethod()// TypeError: foo.classMethod is not a function

2、如果静态方法包含this关键字,这个this指的是类,而不是实例

class Foo {  static bar () {    this.baz();  }  static baz () {    console.log('hello');  }  baz () {    console.log('world');  }}Foo.bar() // hello

从这个例子还可以看出,静态方法可以与非静态方法重名。

3、父类的静态方法,可以被子类继承。

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

  

八:Class 的静态属性和实例属性

1、ES6 明确规定,Class 内部只有静态方法,没有静态属性

class Foo {}Foo.prop = 1;Foo.prop // 1 

上面的写法为Foo类定义了一个静态属性prop。目前,只有这种写法可行。

2、类的实例属性可以用等式,写入类的定义之中

class MyClass {   myProp = 42;   constructor() {     console.log(this.myProp); // 42   }}let a = new MyClass()

上面代码中,myProp就是MyClass的实例属性。

3、类的静态属性可以用等式,写入类的定义之中。(比实例属性多了static)

class MyClass {      static myProp = 42;      constructor() {        console.log(MyClass.myProp); // 42      }    }    let a = new MyClass()

这个新写法大大方便了静态属性的表达。

// 老写法class Foo {  // ...}Foo.prop = 1;// 新写法class Foo {  static prop = 1;}

上面代码中,老写法的静态属性定义在类的外部。整个类生成以后,再生成静态属性。这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码组织原则。另外,新写法是显式声明(declarative),而不是赋值处理,语义更好。

 

九:new.target 属性

new.target指向当前正在执行的函数。

1、Class 内部调用new.target,返回当前 Class。

class Rectangle {  constructor(length, width) {    console.log(new.target === Rectangle);    this.length = length;    this.width = width;  }}var obj = new Rectangle(3, 4); // 输出 true

2、子类继承父类时,new.target会返回子类。

class Rectangle {  constructor(length, width) {    console.log(new.target === Rectangle);    // ...  }}class Square extends Rectangle {  constructor(length) {    super(length, length);  }}var obj = new Square(3); // 输出 false

这里是对子类进行实例

利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Shape {  constructor() {    if (new.target === Shape) {      throw new Error('本类不能实例化');    }  }}class Rectangle extends Shape {  constructor(length, width) {    super(); // 这个super不可缺少    // ...  }}var x = new Shape();  // 报错var y = new Rectangle(3, 4);  // 正确

子类中的constructor中不可缺少super()。

子类必须在constructor方法中调用super方法,否则新建实例时会报错

这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

转载于:https://www.cnblogs.com/momozjm/p/8290202.html

你可能感兴趣的文章
4.使用NDOUtils将Nagios监控信息存入数据库
查看>>
Android 四大组件之Activity 基础总结(1)
查看>>
我没有抛弃SEO,没有离开度娘,只是选择相信马云
查看>>
我的友情链接
查看>>
关于短信协议
查看>>
我的友情链接
查看>>
eclipse 编码设置
查看>>
我的友情链接
查看>>
D3介绍
查看>>
xhtml 1.0和 html 4.01的区别、规范、选择
查看>>
解决 tomcat 启动服务器内存溢出
查看>>
浏览器环境
查看>>
一步一步学习RHEL7之环境搭建
查看>>
禁用http
查看>>
关于 Tomcat 的报错:ClientAbortException
查看>>
COOKIE和SESSION保持会话
查看>>
Microsoft Azure备份VMware虚拟机_2.配置Azure Backup Server
查看>>
我的友情链接
查看>>
用python实现选择截图区域
查看>>
我的友情链接
查看>>