介绍ES6中的class类:(一) 类的基本语法

发布于:2024-07-01 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、类的由来与简介

1. 简介

  1. 很早很早之前,在JavaScript的世界里,生成实例对象的传统方法是通过构造函数。
    嗯哼?
function Point(x, y) {
  this.x = x;
  this.y = y;
}


Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};


var p = new Point(1, 2);

运行查看:
image.png
这种写法就很JavaScript,尤其是prototype,理解起来会很绕。

  1. 于是乎:ES6中的class就诞生了。
    以后可以通过 class 关键字,可以定义类。
    基本上,ES6class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。上面的代码用 ES6class 改写,就是下面这样:
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  // }, 注意:不要加(','),否则报错
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
var p = new Point(1, 2);

运行如图:
image.png
可以看到里面有一个 constructor 方法,这就是构造方法,而 this 关键字则代表实例对象。也就是说,ES5 的构造函数 Point ,对应 ES6Point 类的构造方法。

  1. 继续向下看:p是两位方式创建的实例对象:
    • Point 构造函数在原型上绑定添加toString 方法,要使用:Point.prototype.toString = fn()
    • 构造函数创建的原型访问:
      image.png
    • Point 类呢,定义 toString 方法,前面不仅没有加 function 这个关键字,直接把函数定义放到constructor`构造方法同级里。竟然就能直接添加到原型上了,所以:类的所有方法都定义在类的 prototype 属性上面
    • class类创建的原型访问:
      image.png

嗯哼,这糖甜不甜?
typeof Point = 'function'类的数据类型就是函数,
Point === Point.prototype.constructor // true 类本身就指向构造函数。

2.constructor 方法

  1. constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。
class Point {
}
// 定义了一个空的类 Point ,JavaScript 引擎会自动为它添加一个空的 constructor 方法。

// 等同于
class Point {
  constructor() {}
}
  1. constructor 方法默认返回实例对象(即 this ),可以自定义返回内容。
class Foo {
  constructor() {
    return {};
  }
}


new Foo() instanceof Foo // false

constructor 函数返回一个全新的对象,结果导致实例对象不是 Foo 类的实例。

  1. 类必须使用 new 调用,否则会报错。
    image.png

3. 类的实例

  1. 实例的属性除非显式定义在其本身(即写在constructor内定义在 this 对象上),否则都是定义在原型上。
//定义类
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') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
  1. 类的所有实例共享一个原型对象
var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__ === p2.__proto__ // true

p1p2 都是 Point 的实例,它们的原型都是 Point.prototype ,所以 proto 属性是相等的。

4. 取值函数(getter)和存值函数(setter

“类”的内部可以使用 getset关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class MyClass {
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: '+value);
  }
}
let inst = new MyClass();

inst.prop = 123; // setter: 123
inst.prop // 'getter'

所以举个栗子:
image.png

5. 属性表达式

类的属性名,可以采用表达式。

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

  [methodName]() {
    // ...
  }
}

效果图:
image.png

6. Class 表达式

与函数一样,类也可以使用表达式的形式定义。

const MyClass = class Me {
  getClassName() {
    return Me.name;
  }
};

上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是 Me ,但是 Me 只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用 MyClass 引用。

let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined

上面代码表示, Me 只在 Class 内部有定义。
如果类的内部没用到的话,可以省略 Me ,也就是可以写成下面的形式。

const MyClass = class { /* ... */ };

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

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

person.sayName(); // "张三"

7. 注意

  1. 严格模式
    类和模块的内部,默认就是严格模式,所以不需要使用 use strict 指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。
  2. 不存在提升
    类不存在变量提升(hoist)。
new Foo(); // ReferenceError
class Foo {}
  1. name 属性
    name 属性总是返回紧跟在 class 关键字后面的类名
class Point {}
Point.name // "Point"

效果图:
image.png

  1. this 的指向
    类的方法内部如果含有 this ,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined

上面代码中, printName 方法中的 this ,默认指向 Logger 类的实例。但是,如果将这个方法提取出来单独使用, this 会指向该方法运行时所在的环境(由于 class 内部是严格模式,所以 this 实际指向的是 undefined ),从而导致找不到 print 方法而报错。

  • 一个比较简单的解决方法是,在构造方法中绑定 this ,这样就不会找不到 print 方法了。
class Logger {
  constructor() {
    this.printName = this.printName.bind(this);
  }

  // ...
}
  • 另一种解决方法是使用箭头函数。
class Obj {
  constructor() {
    this.getThis = () => this;
  }
}

const myObj = new Obj();
myObj.getThis() === myObj // true

箭头函数内部的 this 总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以 this 会总是指向实例对象。

二、 静态方法

  1. 类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上 static 关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()

Foo 类的 classMethod 方法前有 static 关键字,表明该方法是一个静态方法,可以直接在 Foo 类上调用( Foo.classMethod() ),而不是在 Foo 类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。

  1. 如果静态方法包含 this 关键字,这个 this 指的是类,而不是实例。
class Foo {
  static bar() {
    this.baz();
  }
  static baz() {
    console.log('hello');
  }
  baz() {
    console.log('world');
  }
}

Foo.bar() // hello

上面代码中,静态方法 bar 调用了 this.baz ,这里的 this 指的是 Foo 类,而不是 Foo 的实例,等同于调用 Foo.baz 。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。

  1. 父类的静态方法,可以被子类继承。
class Foo {
  static classMethod() {
    return 'hello';
  }
}
class Bar extends Foo {
}

Bar.classMethod() // 'hello'
  1. 静态方法也是可以从 super 对象上调用的。
class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}

Bar.classMethod() // "hello, too"

三、实例属性的新写法

实例属性除了定义在constructor()方法里面的 this 上面,也可以定义在类的最顶层。

class IncreasingCounter {
  constructor() {
    this._count = 0;
  }
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

上面代码中,实例属性 this._count 定义在 constructor() 方法里面。另一种写法是,这个属性也可以定义在类的最顶层,其他都不变。

class IncreasingCounter {
  _count = 0;
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

网站公告

今日签到

点亮在社区的每一天
去签到