console.log(instance.count); // 0
- 未初始化的字段会自动设置为 undefined:
class Incrementor {
count
}
const instance = new Incrementor();
console.assert(instance.hasOwnProperty(‘count’));
console.log(instance.count); // undefined
- 可以进行字段的计算:
const PREFIX = ‘main’;
class Incrementor {
[${PREFIX}Count
] = 0
}
const instance = new Incrementor();
console.log(instance.mainCount); // 0
2. 私有实例字段、方法和访问器
默认情况下,ES6 中所有属性都是公共的,可以在类外检查或修改。下面来看一个例子:
class TimeTracker {
name = ‘zhangsan’;
project = ‘blog’;
hours = 0;
set addHours(hour) {
this.hours += hour;
}
get timeSheet() {
return ${this.name} works ${this.hours || 'nothing'} hours on ${this.project}
;
}
}
let person = new TimeTracker();
person.addHours = 2; // 标准 setter
person.hours = 4; // 绕过 setter 进行设置
person.timeSheet;
可以看到,在类中没有任何措施可以防止在不调用 setter 的情况下更改属性。
而私有类字段将使用哈希#前缀定义,从上面的示例中,我们可以修改它以包含私有类字段,以防止在类方法之外更改属性:
class TimeTracker {
name = ‘zhangsan’;
project = ‘blog’;
#hours = 0; // 私有类字段
set addHours(hour) {
this.#hours += hour;
}
get timeSheet() {
return ${this.name} works ${this.#hours || 'nothing'} hours on ${this.project}
;
}
}
let person = new TimeTracker();
person.addHours = 4; // 标准 setter
person.timeSheet // zhangsan works 4 hours on blog
当我们尝试在 setter 方法之外修改私有类字段时,就会报错:
person.hours = 4 // Error Private field ‘#hours’ must be declared in an enclosing class
我们还可以将方法或 getter/setter 设为私有,只需要给这些方法名称前面加#即可:
class TimeTracker {
name = ‘zhangsan’;
project = ‘blog’;
#hours = 0; // 私有类字段
set #addHours(hour) {
this.#hours += hour;
}
get #timeSheet() {
return ${this.name} works ${this.#hours || 'nothing'} hours on ${this.project}
;
}
constructor(hours) {
this.#addHours = hours;
console.log(this.#timeSheet);
}
}
let person = new TimeTracker(4); // zhangsan works 4 hours on blog
由于尝试访问对象上不存在的私有字段会发生异常,因此需要能够检查对象是否具有给定的私有字段。可以使用 in 运算符来检查对象上是否有私有字段:
class Example {
#field
static isExampleInstance(object) {
return #field in object;
}
}
查看更多公有和私有字段提案信息:https://github.com/tc39/proposal-class-fields
3. 静态公共字段
在ES6中,不能在类的每个实例中访问静态字段或方法,只能在原型中访问。ES 2022 将提供一种在 JavaScript 中使用 static 关键字声明静态类字段的方法。下面来看一个例子:
class Shape {
static color = ‘blue’;
static getColor() {
return this.color;
}
getMessage() {
return color:${this.color}
;
}
}
我们可以从类本身访问静态字段和方法:
console.log(Shape.color); // blue
console.log(Shape.getColor()); // blue
console.log(‘color’ in Shape); // true
console.log(‘getColor’ in Shape); // true
console.log(‘getMessage’ in Shape); // false
实例不能访问静态字段和方法:
const shapeInstance = new Shape();
console.log(shapeInstance.color); // undefined
console.log(shapeInstance.getColor); // undefined
console.log(shapeInstance.getMessage());// color:undefined
静态字段只能通过静态方法访问:
console.log(Shape.getColor()); // blue
console.log(Shape.getMessage()); //TypeError: Shape.getMessage is not a function
这里的 Shape.getMessage() 就报错了,这是因为 getMessage 不是一个静态函数,所以它不能通过类名 Shape 访问。可以通过以下方式来解决这个问题:
getMessage() {
return color:${Shape.color}
;
}
静态字段和方法是从父类继承的:
class Rectangle extends Shape { }
console.log(Rectangle.color); // blue
console.log(Rectangle.getColor()); // blue
console.log(‘color’ in Rectangle); // true
console.log(‘getColor’ in Rectangle); // true
console.log(‘getMessage’ in Rectangle); // false
4. 静态私有字段和方法
与私有实例字段和方法一样,静态私有字段和方法也使用哈希 (#) 前缀来定义:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
getMessage() {
return color:${Shape.#getColor()}
;
}
}
const shapeInstance = new Shape();
shapeInstance.getMessage(); // color:blue
私有静态字段有一个限制:只有定义私有静态字段的类才能访问该字段。这可能在我们使用 this 时导致出乎意料的情况:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
static getMessage() {
return color:${this.#color}
;
}
getMessageNonStatic() {
return color:${this.#getColor()}
;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // Uncaught TypeError: Cannot read private member #color from an object whose class did not declare it
const rectangle = new Rectangle();
console.log(rectangle.getMessageNonStatic()); // TypeError: Cannot read private member #getColor from an object whose class did not declare it
在这个例子中,this 指向的是 Rectangle 类,它无权访问私有字段 #color。当我们尝试调用 Rectangle.getMessage() 时,它无法读取 #color 并抛出了 TypeError。可以这样来进行修改:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
static getMessage() {
return ${Shape.#color}
;
}
getMessageNonStatic() {
return color:${Shape.#getColor()} color
;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // color:blue
const rectangle = new Rectangle();
console.log(rectangle.getMessageNonStatic()); // color:blue
静态字段目前是比较稳定的,并且提供了各种实现:
5. 类静态初始化块
静态私有和公共字段只能让我们在类定义期间执行静态成员的每个字段初始化。如果我们需要在初始化期间像 try … catch 一样进行异常处理,就不得不在类之外编写此逻辑。该提案就提供了一种在类声明/定义期间评估静态初始化代码块的优雅方法,可以访问类的私有字段。
先来看一个例子:
class Person {
static GENDER = “Male”
static TOTAL_EMPLOYED;
static TOTAL_UNEMPLOYED;
try {
// …
} catch {
// …
}
}
上面的代码就会引发错误,可以使用类静态块来重构它,只需将try…catch包裹在 static 中即可:
class Person {
static GENDER = “Male”
static TOTAL_EMPLOYED;
static TOTAL_UNEMPLOYED;
static {
try {
// …
} catch {
// …
}
}
}
此外,类静态块提供对词法范围的私有字段和方法的特权访问。这里需要在具有实例私有字段的类和同一范围内的函数之间共享信息的情况下很有用。
let getData;
class Person {
#x
constructor(x) {
this.#x = { data: x };
}
static {
getData = (obj) => obj.#x;
}
}
function readPrivateData(obj) {
return getData(obj).data;
}
const john = new Person([2,4,6,8]);
readPrivateData(john); // [2,4,6,8]
这里,Person 类与 readPrivateData 函数共享了私有实例属性。
三、Temporal
JavaScript 中的日期处理 Date() 对象一直是饱受诟病,该对象是1995 年受到 Java 的启发而实现的,自此就一直没有改变过。虽然Java已经放弃了这个对象,但是 Date() 仍保留在 JavaScript 中来实现浏览器的兼容。
Date() API 存在的问题:
-
只支持UTC和用户的PC时间;
-
不支持公历以外的日历;
-
字符串到日期解析容易出错;
-
Date 对象是可变的,比如:
const today = new Date();
const tomorrow = new Date(today.setDate(today.getDate() + 1));
console.log(tomorrow);
console.log(today);
此时,两个时间输出是一样的,不符合我们的预期。正因为 Date() 对象存在的种种问题。平时我们经常需要借助moment.js
、Day.js
等日期库,但是它们的体积较大,有时一个简单的日期处理就需要引入一个库,得不偿失。
目前,由于Date API 在很多库和浏览器引擎中的广泛使用,没有办法修复API的不好的部分。而改变Date API 的工作方式也很可能会破坏许多网站和库。
正因如此,TC39提出了一个全新的用于处理日期和时间的标准对象和函数——Temporal。新的Temporal API 提案旨在解决Date API的问题。它为 JavaScript 日期/时间操作带来了以下修复:
-
仅可以创建和处理不可变Temporal对象;
-
提供用于日期和时间计算的简单 API;
-
支持所有时区;
-
从 ISO-8601 格式进行严格的日期解析;
-
支持非公历。
Temporal 将取代 Moment.js 之类的库,这些库很好地填补了 JavaScript 中的空白,这种空白非常普遍,因此将功能作为语言的一部分更有意义。
由于该提案还未正式发布,所以,可以借助官方提供的prlyfill来测试。首选进行安装:
npm install @js-temporal/polyfill
导入并使用:
import { Temporal } from ‘@js-temporal/polyfill’;
console.log(Temporal);
Temporal 对象如下:
下面就来看看 Temporal 对象有哪些实用的功能。
1. 当前时间和日期
Temporal.Now 会返回一个表示当前日期和时间的对象:
// 自1970年1月1日以来的时间(秒和毫秒)
Temporal.Now.instant().epochSeconds;
Temporal.Now.instant().epochMilliseconds;
// 当前位置的时间
Temporal.Now.zonedDateTimeISO();
// 当前时区
Temporal.Now.timeZone();
// 指定时区的当前时间
Temporal.Now.zonedDateTimeISO(‘Europe/London’);
2. 实例时间和日期
Temporal.Instant 根据 ISO 8601 格式的字符串返回一个表示日期和时间的对象,结果会精确到纳秒:
Temporal.Instant.from(‘2022-02-01T05:56:78.999999999+02:00[Europe/Berlin]’);
// 输出结果:2022-02-01T03:57:18.999999999Z
Temporal.Instant.from(‘2022-02-011T05:06+07:00’);
// 输出结果:2022-01-31T22:06:00Z
除此之外,我们还可以获取纪元时间的对应的日期(UTC 1970年1月1日0点是纪元时间):
Temporal.Instant.fromEpochSeconds(1.0e8);
// 输出结果:1973-03-03T09:46:40Z
3. 时区日期和时间
Temporal.ZonedDateTime 返回一个对象,该对象表示在特定时区的日期/时间:
new Temporal.ZonedDateTime(
1234567890000, // 纪元时间
Temporal.TimeZone.from(‘Europe/London’), // 时区
Temporal.Calendar.from(‘iso8601’) // 默认日历
);
Temporal.ZonedDateTime.from(‘2025-09-05T02:55:00+02:00[Africa/Cairo]’);
Temporal.Instant(‘2022-08-05T20:06:13+05:45’).toZonedDateTime(‘+05:45’);
// 输出结果:
Temporal.ZonedDateTime.from({
timeZone: ‘America/New_York’,
year: 2025,
month: 2,
day: 28,
hour: 10,
minute: 15,
second: 0,
millisecond: 0,
microsecond: 0,
nanosecond: 0
});
// 输出结果:2025-02-28T10:15:00-05:00[America/New_York]
4. 简单的日期和时间
我们并不会总是需要使用精确的时间,因此 Temporal API 提供了独立于时区的对象。这些可以用于更简单的活动。
-
Temporal.PlainDateTime:指日历日期和时间;
-
Temporal.PlainDate:指特定的日历日期;
-
Temporal.PlainTime:指一天中的特定时间;
-
Temporal.PlainYearMonth:指没有日期成分的日期,例如“2022 年 2 月”;
-
Temporal.PlainMonthDay:指没有年份的日期,例如“10 月 1 日”。
它们都有类似的构造函数,以下有两种形式来创建简单的时间和日期:
new Temporal.PlainDateTime(2021, 5, 4, 13, 14, 15);
Temporal.PlainDateTime.from(‘2021-05-04T13:14:15’);
new Temporal.PlainDate(2021, 5, 4);
Temporal.PlainDate.from(‘2021-05-04’);
new Temporal.PlainTime(13, 14, 15);
Temporal.PlainTime.from(‘13:14:15’);
new Temporal.PlainYearMonth(2021, 4);
Temporal.PlainYearMonth.from(‘2019-04’);
new Temporal.PlainMonthDay(3, 14);
Temporal.PlainMonthDay.from(‘03-14’);
5. 日期和时间值
所有 Temporal 对象都可以返回特定的日期/时间值。例如,使用ZonedDateTime:
const t1 = Temporal.ZonedDateTime.from(‘2025-12-07T03:24:30+02:00[Africa/Cairo]’);
t1.year; // 2025
t1.month; // 12
t1.day; // 7
t1.hour; // 3
t1.minute; // 24
t1.second; // 30
t1.millisecond; // 0
t1.microsecond; // 0
t1.nanosecond; // 0
其他有用的属性包括:
-
dayOfWeek(周一为 1 至周日为 7)
-
dayOfYear(1 至 365 或 366)
-
weekOfYear(1 到 52,有时是 53)
-
daysInMonth(28、29、30、31)
-
daysInYear(365 或 366)
-
inLeapYear(true或false)
6. 比较和排序日期
所有 Temporal 对象都可以使用 compare() 返回整数的函数进行比较。例如,比较两个ZonedDateTime对象:
Temporal.ZonedDateTime.compare(t1, t2);
这个比较结果会有三种情况:
-
当两个时间值相等时,返回 0;
-
当 t1 在 t2 之后时,返回 1;
-
当 t1 在 t2 之前时,但会 -1;
const date1 = Temporal.Now,
const date2 = Temporal.PlainDateTime.from(‘2022-05-01’);
Temporal.ZonedDateTime.compare(date1, date2); // -1
compare() 的结果可以用于数组的 sort() 方法来对时间按照升序进行排列(从早到晚):
const t = [
‘2022-01-01T00:00:00+00:00[Europe/London]’,
‘2022-01-01T00:00:00+00:00[Africa/Cairo]’,
‘2022-01-01T00:00:00+00:00[America/New_York]’
].map(d => Temporal.ZonedDateTime.from(d))
.sort(Temporal.ZonedDateTime.compare);
7. 日期计算
提案还提供了几种方法来对任何 Temporal 对象执行日期计算。当传递一个Temporal.Duration对象时,它们都会返回一个相同类型的新的 Temporal,该对象使用years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds 和 nanoseconds 字段来设置时间。
const t1 = Temporal.ZonedDateTime.from(‘2022-01-01T00:00:00+00:00[Europe/London]’);
t1.add({ hours: 8, minutes: 30 }); // 往后8小时30分
t1.subtract({ days: 5 }); // 往前5天
t1.round({ smallestUnit: ‘month’ }); // 四舍五入到最近的月份
until() 和 since() 方法会返回一个对象,该 Temporal.Duration 对象描述基于当前日期/时间的特定日期和时间之前或之后的时间,例如:
t1.until().months; // 到t1还有几个月
t2.until().days; // 到t2还有几天
t3.since().weeks; // t3已经过去了几周
equals() 方法用来确定两个日期/时间值是否相同:
const d1 = Temporal.PlainDate.from(‘2022-01-31’);
const d2 = Temporal.PlainDate.from(‘2023-01-31’);
d1.equals(d2); // false
8. 使用国际化 API 格式化日期
虽然这不是 Temporal API 的一部分,但 JavaScript Intl(国际化)API提供了一个 DateTimeFormat() 构造函数,可以用于格式化 Temporal 或 Date 对象:
const d = new Temporal.PlainDate(2022, 3, 14);
// 美国日期格式:3/14/2022
new Intl.DateTimeFormat(‘en-US’).format(d);
// 英国日期格式:14/3/2022
new Intl.DateTimeFormat(‘en-GB’).format(d);
// 西班牙长日期格式:miércoles, 14 de abril de 2022
new Intl.DateTimeFormat(‘es-ES’, { dateStyle: ‘full’ }).format(d);
附:
-
TC39 关于 Temporal 的提案进度:https://tc39.es/proposal-temporal/
-
Chrome 关于 Temporal 的实现进度:https://chromestatus.com/feature/5668291307634688#details
四、内置对象
1. Object.hasOwn()
在ES2022之前,可以使用 Object.prototype.hasOwnProperty() 来检查一个属性是否属于对象。
提案中的 Object.hasOwn 特性是一种更简洁、更可靠的检查属性是否直接设置在对象上的方法。
const example = {
property: ‘123’
};
console.log(Object.prototype.hasOwnProperty.call(example, ‘property’));
console.log(Object.hasOwn(example, ‘property’));
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
14 de abril de 2022
new Intl.DateTimeFormat(‘es-ES’, { dateStyle: ‘full’ }).format(d);
附:
-
TC39 关于 Temporal 的提案进度:https://tc39.es/proposal-temporal/
-
Chrome 关于 Temporal 的实现进度:https://chromestatus.com/feature/5668291307634688#details
四、内置对象
1. Object.hasOwn()
在ES2022之前,可以使用 Object.prototype.hasOwnProperty() 来检查一个属性是否属于对象。
提案中的 Object.hasOwn 特性是一种更简洁、更可靠的检查属性是否直接设置在对象上的方法。
const example = {
property: ‘123’
};
console.log(Object.prototype.hasOwnProperty.call(example, ‘property’));
console.log(Object.hasOwn(example, ‘property’));
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-WebCrkIW-1715348117496)]
[外链图片转存中…(img-e72j5sKQ-1715348117496)]
[外链图片转存中…(img-mSFkCocD-1715348117496)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!