而私有类字段将使用哈希#前缀定义,从上面的示例中,我们可以修改它以包含私有类字段,以防止在类方法之外更改属性:
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’));
2. at()
at() 是一个数组方法,用于通过给定索引来获取数组元素。当给定索引为正时,这种新方法与使用括号表示法访问具有相同的行为。当给出负整数索引时,就会从数组的最后一项开始检索:
const array = [0,1,2,3,4,5];
console.log(array[array.length-1]); // 5
console.log(array.at(-1)); // 5
console.log(array[array.lenght-2]); // 4
console.log(array.at(-2)); // 4
除了数组,字符串也可以使用at()方法进行索引:
const str = “hello world”;
console.log(str[str.length - 1]); // d
console.log(str.at(-1)); // d
3. cause
在 ECMAScript 2022 提案中,new Error() 中可以指定导致它的原因:
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
// ···
} catch (error) {
throw new Error(
While processing ${filePath}
,
{cause: error}
);
}
});
}
4. 正则表达式匹配索引
这个新提案已经进入第 4 阶段,它将允许我们利用 d 字符来表示我们想要匹配字符串的开始和结束索引。以前,我们只能在字符串匹配操作期间获得一个包含提取的字符串和索引信息的数组。在某些情况下,这是不够的。因此,在这个新提案中,如果设置标志 /d,将额外获得一个带有开始和结束索引的数组。
const matchObj = /(a+)(b+)/d.exec(‘aaaabb’);
console.log(matchObj[1]) // ‘aaaa’
console.log(matchObj[2]) // ‘bb’
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:前端)
![](https://img-blog.csdnimg.cn/img_convert/a0b6c222364d211a96269d9889691964.jpeg)
最后
技术是没有终点的,也是学不完的,最重要的是活着、不秃。零基础入门的时候看书还是看视频,我觉得成年人,何必做选择题呢,两个都要。喜欢看书就看书,喜欢看视频就看视频。最重要的是在自学的过程中,一定不要眼高手低,要实战,把学到的技术投入到项目当中,解决问题,之后进一步锤炼自己的技术。
技术学到手后,就要开始准备面试了,找工作的时候一定要好好准备简历,毕竟简历是找工作的敲门砖,还有就是要多做面试题,复习巩固。有需要面试题资料的朋友点击这里可以领取。
});
}
4. 正则表达式匹配索引
这个新提案已经进入第 4 阶段,它将允许我们利用 d 字符来表示我们想要匹配字符串的开始和结束索引。以前,我们只能在字符串匹配操作期间获得一个包含提取的字符串和索引信息的数组。在某些情况下,这是不够的。因此,在这个新提案中,如果设置标志 /d,将额外获得一个带有开始和结束索引的数组。
const matchObj = /(a+)(b+)/d.exec(‘aaaabb’);
console.log(matchObj[1]) // ‘aaaa’
console.log(matchObj[2]) // ‘bb’
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-U7CmoXSc-1712409131478)]
[外链图片转存中…(img-O67LsQFf-1712409131479)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
[外链图片转存中…(img-b29AFfxI-1712409131479)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:前端)
![](https://img-blog.csdnimg.cn/img_convert/a0b6c222364d211a96269d9889691964.jpeg)
最后
技术是没有终点的,也是学不完的,最重要的是活着、不秃。零基础入门的时候看书还是看视频,我觉得成年人,何必做选择题呢,两个都要。喜欢看书就看书,喜欢看视频就看视频。最重要的是在自学的过程中,一定不要眼高手低,要实战,把学到的技术投入到项目当中,解决问题,之后进一步锤炼自己的技术。
技术学到手后,就要开始准备面试了,找工作的时候一定要好好准备简历,毕竟简历是找工作的敲门砖,还有就是要多做面试题,复习巩固。有需要面试题资料的朋友点击这里可以领取。
[外链图片转存中…(img-AmJaMHwf-1712409131480)]