头图

5 New JavaScript Features You Must Learn

Maybe you and I have never met, but it is very likely that we will meet each other late, I am a front-end fat head fish

foreword

JavaScript is constantly upgrading and iterating, and more and more new features make our code writing concise and interesting. This article will introduce 5 new features and study them together.

1. # Use "Object.hasOwn" instead of "in" operator

Sometimes, when we want to know if a property exists on an object, we usually use the "in" operator or "obj.hasOwnProperty", but they all have their own drawbacks.

in

The "in" operator returns true if the specified property is in the object or its prototype chain.

 const Person = function (age) {
  this.age = age
}
Person.prototype.name = 'fatfish'

const p1 = new Person(24)
console.log('age' in p1) // true 
console.log('name' in p1) // true  注意这里

obj.hasOwnProperty

hasOwnProperty method will return a boolean value, indicating whether the object's own properties have corresponding values (properties on the prototype chain will not be read).

 const Person = function (age) {
  this.age = age
}
Person.prototype.name = 'fatfish'

const p1 = new Person(24)
console.log(p1.hasOwnProperty('age')) // true 
console.log(p1.hasOwnProperty('name')) // fasle  注意这里

obj.hasOwnProperty It is possible to filter out properties on the prototype chain, but in some cases it is still not safe.

 Object.create(null).hasOwnProperty('name')
// Uncaught TypeError: Object.create(...).hasOwnProperty is not a function

Object.hasOwn

Don't worry, we can use Object.hasOwn to avoid these two problems, which is more convenient and safer than the "obj.hasOwnProperty" method.

 let object = { age: 24 }
Object.hasOwn(object, 'age') // true
let object2 = Object.create({ age: 24 })
Object.hasOwn(object2, 'age') // false  
let object3 = Object.create(null)
Object.hasOwn(object3, 'age') // false

2. # Use "#" to declare private properties

In the past, we generally used _ to represent private attributes, but it is not reliable and will be modified externally.

 class Person {
  constructor (name) {
    this._money = 1
    this.name = name
  }
  get money () {
    return this._money
  }
  set money (money) {
    this._money = money
  }
  showMoney () {
    console.log(this._money)
  }
}
const p1 = new Person('fatfish')
console.log(p1.money) // 1
console.log(p1._money) // 1
p1._money = 2 // 依旧可以从外部修改_money属性,所以这种做法并不安全
console.log(p1.money) // 2
console.log(p1._money) // 2

Use "#" for truly private properties

 class Person {
  #money=1
  constructor (name) {
    this.name = name
  }
  get money () {
    return this.#money
  }
  set money (money) {
    this.#money = money
  }
  showMoney () {
    console.log(this.#money)
  }
}
const p1 = new Person('fatfish')
console.log(p1.money) // 1
// p1.#money = 2 // 没法从外部直接修改
p1.money = 2
console.log(p1.money) // 2
console.log(p1.#money) // Uncaught SyntaxError: Private field '#money' must be declared in an enclosing class

3. # has a useful "number separator"

Looking directly at the example, I was stunned...

 const sixBillion = 6000000000
// ❌ 难以阅读
const sixBillion2 = 6000_000_000
// ✅ 更加易于阅读
console.log(sixBillion2) // 6000000000

Of course, you can also use "_" for calculation

 const sum = 1000 + 6000_000_000 // 6000001000

4. # Use "?." to simplify "&&" and ternary operators

You must be very familiar with these examples. Is there a way we can simplify it?

 const obj = null
console.log(obj && obj.name)
const $title = document.querySelector('.title')
const title = $title ? title.innerText : undefined

"?."

 const obj = null
console.log(obj?.name)
const $title = document.querySelector('.title')
const title = $title?.innerText

Tips

General usage of ?.

  1. obj?.prop object properties
  2. obj?.[expr] object properties
  3. func?.(...args) execute function

5. # Use "BigInt" to support large number calculations

Number calculations beyond "Number.MAX_SAFE_INTEGER" in JS will be unsafe.

Example:

 Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
// Math.pow(2, 53) => 9007199254740992
// Math.pow(2, 53) + 1 => 9007199254740992

Using "BigInt" completely avoids this problem

 BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false

At last

I hope to share practical, basic and advanced knowledge points with you all the time, get off work early and fish happily together.

I look forward to your following me in the Nuggets : Front-end Fat Head Fish , you can also find me in the public account: Front-end Fat Head Fish .


3.7k 声望
6.1k 粉丝
0 条评论
推荐阅读
面试官:Vue3响应式系统都不会写,还敢说精通?
也许你我素未谋面,但很可能相见恨晚,我是前端胖头鱼前言都说今年是最惨工作年,大厂裁员,小厂跟风,简历投了几百封回信的寥寥无几,金三银四怕是成了铜三铁四,冷冷清清,凄凄惨惨。但是今天的主角,小帅同学...

前端胖头鱼6阅读 5.5k评论 2

封面图
安全地在前后端之间传输数据 - 「3」真的安全吗?
在「2」注册和登录示例中,我们通过非对称加密算法实现了浏览器和 Web 服务器之间的安全传输。看起来一切都很美好,但是危险就在哪里,有些人发现了,有些人嗅到了,更多人却浑然不知。就像是给门上了把好锁,还...

边城31阅读 7.2k评论 5

封面图
涨姿势了,有意思的气泡 Loading 效果
今日,群友提问,如何实现这么一个 Loading 效果:这个确实有点意思,但是这是 CSS 能够完成的?没错,这个效果中的核心气泡效果,其实借助 CSS 中的滤镜,能够比较轻松的实现,就是所需的元素可能多点。参考我们...

chokcoco20阅读 2.1k评论 2

在前端使用 JS 进行分类汇总
最近遇到一些同学在问 JS 中进行数据统计的问题。虽然数据统计一般会在数据库中进行,但是后端遇到需要使用程序来进行统计的情况也非常多。.NET 就为了对内存数据和数据库数据进行统一地数据处理,发明了 LINQ (L...

边城17阅读 1.9k

封面图
【已结束】SegmentFault 思否写作挑战赛!
SegmentFault 思否写作挑战赛 是思否社区新上线的系列社区活动在 2 月 8 日 正式面向社区所有用户开启;挑战赛中包含多个可供作者选择的热门技术方向,根据挑战难度分为多个等级,快来参与挑战,向更好的自己前进!

SegmentFault思否20阅读 5.6k评论 10

封面图
过滤/筛选树节点
又是树,是我跟树杠上了吗?—— 不,是树的问题太多了!🔗 相关文章推荐:使用递归遍历并转换树形数据(以 TypeScript 为例)从列表生成树 (JavaScript/TypeScript) 过滤和筛选是一个意思,都是 filter。对于列表来...

边城18阅读 7.7k评论 3

封面图
你可能不需要JS!CSS实现一个计时器
CSS现在可不仅仅只是改一个颜色这么简单,还可以做很多交互,比如做一个功能齐全的计时器?样式上并不复杂,主要是几个交互的地方数字时钟的变化开始、暂停操作重置操作如何仅使用 CSS 来实现这样的功能呢?一起...

XboxYan21阅读 1.6k评论 1

封面图
3.7k 声望
6.1k 粉丝
宣传栏