Appearance
Class 基本语法
类的由来
JavaScript 中,生成实例对象是通过构造函数
ES6 引入 Class,作为对象模板,通过class关键字定义。
class是一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法
constructor:构造方法
this关键字:代表实例对象
js
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}类的数据类型就是函数,类本身就指向构造函数
js
typeof Point // "function"
Point === Point.prototype.constructor // true类的所有方法都定义在类的prototype属性上
js
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};实例上调用方法,其实就是调用原型方法
js
class B {}
const b = new B();
b.constructor === B.prototype.constructor // true利用类方法在原型上,可以一次向类添加多个方法
js
class Point {
constructor(){
// ...
}
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});类内部定义方法,不可枚举。与 ES5 行为不一致
js
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]js
var Point = function (x, y) {
// ...
};
Point.prototype.toString = function () {
// ...
};
Object.keys(Point.prototype)
// ["toString"]
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]constructor 方法
constructor方法:类默认方法
调用时机:new命令生成对象实例时,自动调用该方法
- 一个类必须有constructor方法。没有显式定义,默认添加空constructor方法
js
class Point {
}
// 等同于
class Point {
constructor() {}
}- constructor方法默认返回实例对象(即this)
js
class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo
// false- 类必须使用new调用,否则会报错。这是与 普通构造函数的主要区别
类的实例
类的属性和方法,默认定义在原型上。除非显式定义在 实例(this) 上
js
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类的所有实例共享一个原型对象
js
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__ === p2.__proto__
//true__proto__ 并不是语言本身的特性,是各大厂商具体添加的私有属性。不建议使用,建议使用 Object.getPrototypeOf() 代替。
实例属性的新写法
ES2022,实例属性除了可以定义在 consturctor 方法 this 上,也可以定义在类内部的最顶层
js
class IncreasingCounter {
/*
constructor() {
this._count = 0;
}
*/
_count = 0;
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}这种写法,属性是实例属性,而不是原型属性。
getter 和 setter
使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为
js
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'存值函数和取值函数是设置在属性的 Descriptor 对象上,与 ES5 一致
js
var descriptor = Object.getOwnPropertyDescriptor(
MyClass.prototype, "prop"
);
"get" in descriptor // true
"set" in descriptor // true属性表达式
支持变量作为方法名
js
let methodName = 'getArea';
class Square {
constructor(length) {
// ...
}
[methodName]() {
// ...
}
}Class 表达式
表达式的形式定义
js
const MyClass = class Me {
getClassName() {
return Me.name;
}
};类的名字是Me。name 属性在内部可用,指代当前类。
js
let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined类的内部没用到的话,可以省略Me
js
const MyClass = class { /* ... */ };立即执行的 Class
js
let person = new class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('张三');
person.sayName(); // "张三"静态方法
类相当于实例的原型,在类中定义的方法,都会被实例继承。
加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用。static关键字方法又叫静态方法。
js
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function在实例上调用静态方法,会抛出一个错误,表示不存在该方法
静态方法 this 指向类,而不是实例。
js
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello静态方法可以和非静态方法重名
父类的静态方法,可以被子类继承。通过super调用
js
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}静态属性
同静态方法,静态属性是Class 本身的属性,而不是实例对象(this)属性
ES6 规定,Class 内部只有静态方法,没有静态属性
现有提案提供了类的静态属性,写法是在实例属性的前面,加上static关键字
js
// 老写法
class Foo {
// ...
}
Foo.prop = 1;
// 新写法
class Foo {
static prop = 1;
}老写法:类生成以后,再生成静态属性
私有方法和私有属性
ES6 不提供私有方法和私有属性,只能通过变通方法模拟实现
早期方案
- 命名上加以区别
js
class Widget {
// 公有方法
foo (baz) {
this._bar(baz);
}
// 私有方法
_bar(baz) {
return this.snaf = baz;
}
// ...
}- 将私有方法移出类,因为类内部方法都是对外可见的。
js
class Widget {
foo (baz) {
bar.call(this, baz);
}
// ...
}
function bar(baz) {
return this.snaf = baz;
}- Symbol值的唯一性
js
const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class myClass{
// 公有方法
foo(baz) {
this[bar](baz);
}
// 私有方法
[bar](baz) {
return this[snaf] = baz;
}
// ...
};一般情况下无法获取到它们,Reflect.ownKeys依然可以拿到它们
正式写法
ES2022为class添加了私有属性,方法是在属性名之前使用 #
js
class IncreasingCounter {
#count = 0;
get value() {
console.log('Getting the current value!');
return this.#count;
}
increment() {
this.#count++;
}
}私有属性,只能在类的内部使用,外部调用会报错
js
const counter = new IncreasingCounter();
counter.#count // 报错
counter.#count = 42 // 报错不管在类的内部或外部,读取一个不存在的私有属性,也会报错
私有属性也可以设置 getter 和 setter 方法
js
class Counter {
#xValue = 0;
constructor() {
console.log(this.#x);
}
get #x() { return this.#xValue; }
set #x(value) {
this.#xValue = value;
}
}私有属性不限于从this引用,只要是在类的内部,实例也可以引用私有属性
js
class Foo {
#privateValue = 42;
static getPrivateValue(foo) {
return foo.#privateValue;
}
}
Foo.getPrivateValue(new Foo()); // 42加上static关键字,表示静态的私有属性或私有方法。但只能在 class 内部调用。
js
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() // 报错in 运算符
直接访问某个类不存在的私有属性会报错,但是访问不存在的公开属性不会报错。
这个特性,可以判断某个对象是否为类的实例。
js
class C {
#brand;
static isC(obj) {
try {
obj.#brand;
return true;
} catch {
return false;
}
}
}通过 try...catch 判断某个私有属性是否存在,可读性太差
ES2022 改进了in运算符,可以用来判断私有属性
js
class A {
#foo = 0;
m() {
console.log(#foo in this); // true
console.log(#bar in this); // false
}
}子类从父类继承的私有属性,也可以使用in运算符来判断
js
class A {
#foo = 0;
static test(obj) {
console.log(#foo in obj);
}
}
class SubA extends A {};
A.test(new SubA()) // true注意:Object.create、Object.setPrototypeOf形成的继承无法传递私有属性,所以 in 运算符在其中无效
静态块
场景:静态属性之间存在依赖关系
解决:
- 将初始化在类的外部,但会把类逻辑写在外部
js
class C {
static x = 234;
static y;
static z;
}
C.y = C.x + 1
C.z = C.x - 1
console.log(C.x,C.y,C.z)- 在constructor方法中处理,但需要通过实例调用,并且每次新建实例都会调用
js
class C {
constructor(){
this.x = 234
this.y = this.x + 1
this.z = this.x - 1
}
}
const c = new C()ES2022 引入静态块(static block),允许在类的内部设置一个代码块
调用时机:在类生成时运行一次(仅一次)
主要作用:静态属性进行初始化
js
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 = ...;
}
}
}每个类只能有一个静态块,在静态属性声明后运行。静态块的内部不能有return语句。
静态块内部使用类名或this,指代当前类
js
class C {
static x = 1;
static {
this.x; // 1
// 或者
C.x; // 1
}
}静态块还有一个作用,将私有属性与类的外部代码分享
js
let getX;
export class C {
#x = 1;
static {
getX = obj => obj.#x;
}
}
console.log(getX(new C())); // 1类的注意点
- 默认开启严格模式
- 不存在提升
类不存在变量提升(hoist)
js
new Foo(); // ReferenceError
class Foo {}- name 属性
ES6 的类只是 ES5 的构造函数的一层包装,函数特性都被Class继承,包括name属性
js
class Point {}
Point.name // "Point"- Generator 方法
类的Symbol.iterator方法前有一个星号,表示该方法是 Generator 函数。
js
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world- this 指向
类的方法内部如果含有this,它默认指向类的实例
js
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默认指向实例,但是单独提取方法(解构)后,this会指向该方法运行时所在的环境。(由于 class 内部是严格模式,所以 this 实际指向的是undefined)
解决:
方法1:在构造方法中绑定this
js
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}方法2:使用箭头函数
js
class Logger {
constructor() {
this.printName = (name='there')=>{
this.print(`Hello ${name}`);
}
}
// ...
}方法3:使用Proxy,获取方法的时候,自动绑定this
js
function selfish (target) {
const cache = new WeakMap();
const handler = {
get (target, key) {
const value = Reflect.get(target, key);
if (typeof value !== 'function') {
return value;
}
if (!cache.has(value)) {
cache.set(value, value.bind(target));
}
return cache.get(value);
}
};
const proxy = new Proxy(target, handler);
return proxy;
}
const logger = selfish(new Logger());new.target 属性
ES6 为new命令引入了一个new.target属性。
new.target属性:一般用在构造函数之中,返回new命令作用于的那个构造函数
确保构造函数只能通过new命令调用
js
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.target会返回子类
利用这个特点,可以写出不能独立使用、必须继承后才能使用的类
js
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); // 正确