必须学习的5个JavaScript新特性写起来变得简洁有趣。本文将介绍5个新特性,一起来学习吧。1.#使用“Object.hasOwn”而不是“in”运算符有时,我们想知道对象上是否有属性,一般使用“in”运算符或“obj.hasOwnProperty”,但它们各有缺陷。in如果指定的属性在对象或其原??型链中,则“in”运算符返回true。constPerson=function(age){this.age=age}Person.prototype.name='fatfish'constp1=newPerson(24)console.log('age'inp1)//trueconsole.log('name'inp1)//true这里注意obj.hasOwnPropertyhasOwnProperty方法会返回一个布尔值,表示对象自身的属性是否有对应的值(不会读取原型链上的属性)。constPerson=function(age){this.age=age}Person.prototype.name='fatfish'constp1=newPerson(24)console.log(p1.hasOwnProperty('age'))//trueconsole.log(p1.hasOwnProperty('name'))//fasle注意obj.hasOwnProperty已经可以过滤掉原型链上的属性,但是在某些情况下,还是不安全的。Object.create(null).hasOwnProperty('name')//UncaughtTypeError:Object.create(...).hasOwnPropertyisnotafunctionObject.hasOwn不用担心,我们可以使用Object.hasOwn来避免这两个问题,这比“obj.hasOwnProperty”方法更方便也更安全。letobject={age:24}Object.hasOwn(object,'age')//trueletobject2=Object.create({age:24})Object.hasOwn(object2,'age')//falseletobject3=Object.create(null)Object.hasOwn(object3,'age')//false2.#在使用“#”声明私有属性之前,我们通常使用_来表示私有属性,但是不靠谱,还是会被修改外部。classPerson{constructor(name){this._money=1this.name=name}getmoney(){returnthis._money}setmoney(money){this._money=money}showMoney(){console.log(this._money)}}constp1=newPerson('fatfish')console.log(p1.money)//1console.log(p1._money)//1p1._money=2//_money属性仍然可以修改外面,所以这种方式不安全console.log(p1.money)//2console.log(p1._money)//2使用“#”实现真正的私有属性classPerson{#money=1constructor(name){this.name=name}getmoney(){returnthis.#money}setmoney(money){this.#money=money}showMoney(){console.log(this.#money)}}constp1=newPerson('fatfish')console.log(p1.money)//1//p1.#money=2//不能直接从外部修改p1.money=2console.log(p1.money)//2console.log(p1.#money)//UncaughtSyntaxError:Privatefield'#money'mustbedeclaredinananenclosingclass3.#有一个有用的“数字分隔符”直接看例子e,我惊呆了...constsixBillion=6000000000//?难读constsixBillion2=6000_000_000//?读起来更容易console.log(sixBillion2)//6000000000也可以使用“_”来计算constsum=1000+6000_000_000//60000010004.#使用“?”。简化“&&”和三元运算符的例子,你一定很熟悉,有什么办法可以简化吗?constobj=nullconsole.log(obj&&obj.name)const$title=document.querySelector('.title')consttitle=$title?title.innerText:未定义“?”constobj=nullconsole.log(obj?.name)const$title=document.querySelector('.title')consttitle=$title?.innerTextTips?.一般用法obj?.prop对象属性obj?.[expr]对象属性func?.(...args)执行函数5.#使用“BigInt”支持大数计算。在JS中超过“Number.MAX_SAFE_INTEGER”的数字计算将是不安全的。示例: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最后,希望时时刻刻与大家分享实用的、基础的、进阶的知识点,一起早点下班,摸鱼开心。期待大家关注掘金:前端黑头鱼,也可以在公众号:前端黑头鱼找到我。
