Skip to main content

class

class类的定义方法

1、es5定义类:

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);

es6定义类:通过class关键字

class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}

toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

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

Point类除了构造方法,还定义了一个toString()方法。注意,定义toString()方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法与方法之间不需要逗号分隔,加了会报错。

2、ES6 的类,完全可以看作构造函数的另一种写法。

class Point {
// ...
}

typeof Point // "function"
Point === Point.prototype.constructor // true

上面代码表明,类的数据类型就是函数,类本身就指向构造函数。

2、es6的使用方法和构造函数的方法一样,直接使用new关键字。

2、class的所有方法都定义在prototype(显示原型)属性上。

class Point {
constructor() {
// ...
}

toString() {
// ...
}

toValue() {
// ...
}
}

// 等同于

Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};

上面代码中,constructor()toString()toValue()这三个方法,其实都是定义在Point.prototype上面。

在类的实例上调用方法,就是调用原型上的方法。

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

b---实例化对象,prototype--显示原型

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

class Point {
constructor(){
// ...
}
}

Object.assign(Point.prototype, {
toString(){},
toValue(){}
});

⭕️4、类的内部定义的方法都是不可枚举的,es5的都是可枚举的。

es6:class Point {
constructor(x, y) {
// ...
}

toString() {
// ...
}
}

Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

es5:var Point = function (x, y) {
// ...
};

Point.prototype.toString = function () {
// ...
};

Object.keys(Point.prototype)
// ["toString"]
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

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

class Point {
}

// 等同于
class Point {
constructor() {}
}
//constructor()方法默认返回实例对象(即this),可以指定返回另外一个对象。

class Foo {
constructor() {
return Object.create(null); //创建一个新的空对象
}
}

new Foo() instanceof Foo
// false

上面代码中,constructor()函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

6、class类必须用new调用,否则报错。 es5不用new也可以执行。

class Point {
// ...
}

// 报错
var point = Point(2, 3);

// 正确
var point = new Point(2, 3);

7、实例的属性除非定义在它显示原型(constructor)的本身上,否则都是定义在原型上(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') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

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

hasOwnProperty 方法判断某对象是否含有特定的自身属性,表示是否有自己的属性,会查找一个对象是否有某个属性,但是不会去查找它的原型链。

8、与 ES5 一样,类的所有实例共享一个原型对象。

var p1 = new Point(2,3);
var p2 = new Point(3,2);

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

p1和p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。

可以通过实例的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"

在p1的原型上添加了一个printName()方法,由于p1的原型就是p2的原型,因此p2也可以调用这个方法。而且,此后新建的实例p3也可以调用这个方法。

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

可以使用 Object.getPrototypeOf()方法来获取实例对象的原型,然后再来为原型添加方法/属性。

9、类的内部也有get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class MyClass {
constructor() {
// ...
}
get prop() {
return 'getter';
}
set prop(value) {
console.log('setter: '+value);
}
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

存值函数和取值函数是设置在html属性的 Descriptor(描述) 对象上的,与es5一样。

class CustomHTMLElement {
constructor(element) {
this.element = element;
}

get html() {
return this.element.innerHTML;
}

set html(value) {
this.element.innerHTML = value;
}
}

var descriptor = Object.getOwnPropertyDescriptor(
CustomHTMLElement.prototype, "html"
);

"get" in descriptor // true
"set" in descriptor // true

Object.getOwnPropertyDescriptor() 方法返回指定对象上一个自有属性对应的属性描述符。

自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性。

语法:Object.getOwnPropertyDescriptor(obj, prop)

参数:obj需要查找的目标对象; prop目标对象内属性名称

返回值:如果指定的属性存在于对象上,则返回其属性描述符对象(property descriptor),否则返回 undefined。

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

let methodName = 'getArea';

class Square {
constructor(length) {
// ...
}

[methodName]() {
// ...
}
}
上面代码中,Square类的方法名getArea,是从表达式得到的。

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

const MyClass = class Me {
getClassName() {
return Me.name;
}
};
let inst = new MyClass();
inst.getClassName() // Me , 表示,Me只在 Class 内部有定义。
Me.name // ReferenceError: Me is not defined

如果用表达式定义类的话,要注意,这个类的名字是Me,但是Me只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用MyClass引用。 如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。 const MyClass = class { / ... / };

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

let person = new class {
constructor(name) {
this.name = name;
}

sayName() {
console.log(this.name);
}
}('张三');

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

13、class和模块内部默认就是严格模式,所以不需要使用use strict指定运行模式。

class没有变量提升,因为有继承,必须保证子类在父类之后定义。

14、name属性,name属性总是返回紧跟在class关键字后面的类名。

class Point {}
Point.name // "Point"

15、Generator 方法:如果某个方法之前加上星号(),就表示该方法是一个 Generator 函数。*

class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() { //Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个 Generator 函数。
for (let arg of this.args) {
yield arg;
}
}
}

for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world

Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。

Generator函数是es6提供的一种异步编程的解决方案,执行Generator函数会返回一个遍历器对象,可以依次遍历Generator函数内部的每一个状态。

Generator函数有两个特征:
一是,function关键字与函数之间有一个 * ,
二是,函数体内部使用yield表达式,定义不同的内部状态。

调用Generator函数后,函数并不执行,返回遍历器对象。

必须调用遍历器对象的next方法,使得指针移向下一个状态,也就是说,每次调用next方法,内部指针就从函数头部或者上次停下的地方开始执行,直到遇到下一个yield表达式(或return语句为止)。

Generator函数是分段执行的。yield表达式只是暂停的标志,而next方法可以恢复执行。

16、this指向:类的方法内部如果含有this,它默认指向类的实例。

单独使用会报错,解决方法:

在构造方法中绑定this,这样就不会找不到print方法了。 或者使用箭头函数,箭头函数内部的this总是指向定义时所在的对象。 或者使用proxy,获取方法的时候,自动绑定this

17、静态方法:类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
static classMethod() {
return 'hello';
}
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

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

如果静态方法包含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。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。 父类的静态方法,可以被子类继承。

class Foo {
static classMethod() {
return 'hello';
}
}

class Bar extends Foo {
}

Bar.classMethod() // 'hello'
父类Foo有一个静态方法,子类Bar可以调用这个方法。

静态方法也是可以从super对象上调用的。

class Foo {
static classMethod() {
return 'hello';
}
}

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

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

18、实例属性新的写法。

实例属性除了定义在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()方法里面。

另一种写法,这个属性也可以定义在类的最顶层,其他都不变。

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

上面代码中,实例属性_count与取值函数value()和increment()方法,处于同一个层级。这时,不需要在实例属性前面加上this。

这种新写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。

class foo {
bar = 'hello';
baz = 'world';

constructor() {
// ...
}
}

19、静态属性:静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。

class Foo {
}

Foo.prop = 1;
Foo.prop // 1

上面的写法为Foo类定义了一个静态属性prop。

新写法:class Foo {
static prop = 1;
}

20、私有方法和私有属性:是只能在类的内部访问的方法和属性,外部不能访问。

但 ES6 不提供,只能通过变通方法模拟实现。

一种做法是在命名上加以区别。

class Widget {

// 公有方法
foo (baz) {
this._bar(baz);
}

// 私有方法
_bar(baz) {
return this.snaf = baz;
}

// ...
}

上面代码中,_bar()方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。

另一种方法就是索性将私有方法移出类,因为类内部的所有方法都是对外可见的。

class Widget {
foo (baz) {
bar.call(this, baz);
}

// ...
}

function bar(baz) {
return this.snaf = baz;
}

上面代码中,foo是公开方法,内部调用了bar.call(this, baz)。这使得bar()实际上成为了当前类的私有方法。

还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。

const bar = Symbol('bar');
const snaf = Symbol('snaf');

export default class myClass{

// 公有方法
foo(baz) {
this[bar](baz);
}

// 私有方法
[bar](baz) {
return this[snaf] = baz;
}

// ...
};

上面代码中,bar和snaf都是Symbol值,一般情况下无法获取到它们,因此达到了私有方法和私有属性的效果。

但是也不是绝对不行,Reflect.ownKeys()依然可以拿到它们。

const inst = new myClass();

Reflect.ownKeys(myClass.prototype)
// [ 'constructor', 'foo', Symbol(bar) ]

上面代码中,Symbol 值的属性名依然可以从类的外部拿到。

最好用的私有属性方法是在属性名之前,使用#表示

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

上面代码中,#count就是私有属性,只能在类的内部使用(this.#count)。如果在类的外部使用,就会报错。

const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错

上面代码在类的外部,读取私有属性,就会报错。
class Point {
#x;

constructor(x = 0) {
this.#x = +x;
}

get x() {
return this.#x;
}

set x(value) {
this.#x = +value;
}
}

上面代码中,#x就是私有属性,在Point类之外是读取不到这个属性的。由于井号#是属性名的一部分,使用时必须带有#一起使用,所以#x和x是两个不同的属性。

这种写法不仅可以写私有属性,还可以用来写私有方法。

class Foo {
#a;
#b;
constructor(a, b) {
this.#a = a;
this.#b = b;
}
#sum() {
return this.#a + this.#b;
}
printSum() {
console.log(this.#sum());
}
}

上面代码中,#sum()就是一个私有方法。

私有属性也可以设置 getter 和 setter 方法。

class Counter {
#xValue = 0;

constructor() {
super();
// ...
}

get #x() { return #xValue; }
set #x(value) {
this.#xValue = value;
}
}

上面代码中,#xValue是一个私有属性,它的读写都通过get #x()和set #x()来完成。

私有属性不限于从this引用,只要是在类的内部,实例也可以引用私有属性。

class Foo {
#privateValue = 42;
static getPrivateValue(foo) {
return foo.#privateValue;
}
}

Foo.getPrivateValue(new Foo()); // 42

私有属性和私有方法前面,也可以加上static关键字,表示这是一个静态的私有属性或私有方法。

class FakeMath {
static PI = 22 / 7;
static #totallyRandomNumber = 4;

static #computeRandomNumber() {
return FakeMath.#totallyRandomNumber;
}

static random() {
console.log('I heard you like random numbers…')
return FakeMath.#computeRandomNumber();
}
}

FakeMath.PI // 3.142857142857143
FakeMath.random()
// I heard you like random numbers…
// 4
FakeMath.#totallyRandomNumber // 报错
FakeMath.#computeRandomNumber() // 报错

上面代码中,#totallyRandomNumber是私有属性,#computeRandomNumber()是私有方法,只能在FakeMath这个类的内部调用,外部调用就会报错。

21、in运算符

try...catch结构可以用来判断是否存在某个私有属性。

class A {
use(obj) {
try {
obj.#foo;
} catch {
// 私有属性 #foo 不存在
}
}
}

const a = new A();
a.use(a); // 报错

上面示例中,类A并不存在私有属性#foo,所以try...catch报错了。

in运算符,也可以用来判断私有属性。

class A {
use(obj) {
if (#foo in obj) {
// 私有属性 #foo 存在
} else {
// 私有属性 #foo 不存在
}
}
}

上面示例中,in运算符判断当前类A的实例,是否有私有属性#foo,如果有返回true,否则返回false。

in也可以跟this一起配合使用。

class A {
#foo = 0;
m() {
console.log(#foo in this); // true
console.log(#bar in this); // false
}
}

注意,判断私有属性时,in只能用在定义该私有属性的类的内部。

class A {
#foo = 0;
static test(obj) {
console.log(#foo in obj);
}
}

A.test(new A()) // true
A.test({}) // false

class B {
#foo = 0;
}
A.test(new B()) // false

上面示例中,类A的私有属性#foo,只能在类A内部使用in运算符判断,而且只对A的实例返回true,对于其他对象都返回false。

子类从父类继承的私有属性,也可以使用in运算符来判断。

class A {
#foo = 0;
static test(obj) {
console.log(#foo in obj);
}
}

class SubA extends A {};

A.test(new SubA()) // true

上面示例中,SubA从父类继承了私有属性#foo,in运算符也有效。

in运算符对于Object.create()、Object.setPrototypeOf形成的继承,是无效的,因为这种继承不会传递私有属性。

class A {
#foo = 0;
static test(obj) {
console.log(#foo in obj);
}
}
const a = new A();

const o1 = Object.create(a);
A.test(o1) // false
A.test(o1.__proto__) // true

const o2 = {};
Object.setPrototypeOf(o2, A);
A.test(o2) // false
A.test(o2.__proto__) // true

上面示例中,对于修改原型链形成的继承,子类都取不到父类的私有属性,所以in运算符无效。

22、静态块

静态属性的一个问题是,它的初始化要么写在类的外部,要么写在constructor()方法里面。

class C {
static x = 234;
static y;
static z;
}

try {
const obj = doSomethingWith(C.x);
C.y = obj.y
C.z = obj.z;
} catch {
C.y = ...;
C.z = ...;
}

上面示例中,静态属性y和z的值依赖静态属性x,它们的初始化写在类的外部(上例的try...catch代码块)。

另一种方法是写到类的constructor()方法里面。

这两种方法都不是很理想,前者是将类的内部逻辑写到了外部,后者则是每次新建实例都会运行一次。

为了解决这个问题,引入了静态块(static block),允许在类的内部设置一个代码块,在类生成时运行一次,主要作用是对静态属性进行初始化。

class C {
static x = ...;
static y;
static z;

static {
try {
const obj = doSomethingWith(this.x);
this.y = obj.y;
this.z = obj.z;
}
catch {
this.y = ...;
this.z = ...;
}
}
}

上面代码中,类的内部有一个 static 代码块,这就是静态块。它的好处是将静态属性y和z的初始化逻辑,写入了类的内部,而且只运行一次。

每个类只能有一个静态块,在静态属性声明后运行。静态块的内部不能有return语句。

静态块内部可以使用类名或this,指代当前类。

class C {
static x = 1;
static {
this.x; // 1
// 或者
C.x; // 1
}
}

上面示例中,this.x和C.x都能获取静态属性x。

除了静态属性的初始化,静态块还有一个作用,就是将私有属性与类的外部代码分享。

let getX;

export class C {
#x = 1;
static {
getX = obj => obj.#x;
}
}

console.log(getX(new C())); // 1

上面示例中,#x是类的私有属性,如果类外部的getX()方法希望获取这个属性,以前是要写在类的constructor()方法里面,这样的话,每次新建实例都会定义一次getX()方法。现在可以写在静态块里面,这样的话,只在类生成时定义一次。

22、new.target属性

ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。 如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

function Person(name) {
if (new.target !== undefined) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}

// 另一种写法
function Person(name) {
if (new.target === Person) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}

var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三'); // 报错

上面代码确保构造函数只能通过new命令调用。

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

需要注意的是,子类继承父类时,new.target会返回子类。

class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
// ...
}
}

class Square extends Rectangle {
constructor(length, width) {
super(length, width);
}
}

var obj = new Square(3); // 输出 false

上面代码中,new.target会返回子类。

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

class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}

class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}

var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确

上面代码中,Shape类不能被实例化,只能用于继承。 注意,在函数外部,使用new.target会报错。