兴许你我素未谋面,但很可能相见恨晚,我是前端胖头鱼
前言
JavaScript在一直地降级迭代,越来越多的新个性让咱们的代码写起来变得简洁乏味,这篇文章会介绍5个新个性,一起钻研一下把。
1.# 应用"Object.hasOwn"代替“in”操作符
有时,咱们想晓得对象上是否存在某个属性,个别会应用“in”操作符或“obj.hasOwnProperty”,但它们都有各自的缺点。
in
如果指定的属性位于对象或其原型链中,“in”运算符将返回true。
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
办法会返回一个布尔值,示意对象本身属性中是否具备对应的值(原型链上的属性不会读取)。
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
曾经能够过滤掉原型链上的属性,但在某些状况下,它还是不平安。
Object.create(null).hasOwnProperty('name')// Uncaught TypeError: Object.create(...).hasOwnProperty is not a function
Object.hasOwn
别急,咱们能够应用Object.hasOwn
来防止这两个问题,这比“obj.hasOwnProperty”办法更加不便、平安。
let object = { age: 24 }Object.hasOwn(object, 'age') // truelet object2 = Object.create({ age: 24 })Object.hasOwn(object2, 'age') // false let object3 = Object.create(null)Object.hasOwn(object3, 'age') // false
2.# 应用"#"申明公有属性
以前,咱们个别用_
示意公有属性,但它并不靠谱,还是会被内部批改。
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) // 1console.log(p1._money) // 1p1._money = 2 // 仍旧能够从内部批改_money属性,所以这种做法并不平安console.log(p1.money) // 2console.log(p1._money) // 2
应用“#”实现真正公有属性
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 = 2console.log(p1.money) // 2console.log(p1.#money) // Uncaught SyntaxError: Private field '#money' must be declared in an enclosing class
3.# 具备用的"数字分隔符"
间接看例子,惊呆了我...
const sixBillion = 6000000000// ❌ 难以浏览const sixBillion2 = 6000_000_000// ✅ 更加易于浏览console.log(sixBillion2) // 6000000000
当然也能够应用"_"用于计算
const sum = 1000 + 6000_000_000 // 6000001000
4.# 应用"?."简化"&&"和三元运算符
这些例子,你肯定十分相熟,咱们有方法能够简化它吗?
const obj = nullconsole.log(obj && obj.name)const $title = document.querySelector('.title')const title = $title ? title.innerText : undefined
“?.”
const obj = nullconsole.log(obj?.name)const $title = document.querySelector('.title')const title = $title?.innerText
Tips
?. 的个别用法
- obj?.prop 对象属性
- obj?.[expr] 对象属性
- func?.(...args) 执行函数
5.# 应用"BigInt"反对大数计算
JS中超过“Number.MAX_SAFE_INTEGER”的数字计算将是不平安的。
Example:
Math.pow(2, 53) === Math.pow(2, 53) + 1 // true// Math.pow(2, 53) => 9007199254740992// Math.pow(2, 53) + 1 => 9007199254740992
应用"BigInt"齐全能够防止这个问题
BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false
最初
心愿能始终给大家分享实用、根底、进阶的知识点,一起早早上班,高兴摸鱼。
期待你在掘金关注我:前端胖头鱼,也能够在公众号里找到我:前端胖头鱼。