object.create_Object.create(空)

object.create

One of the funnest parts of JavaScript, or any programming language really, is that there are loads of tiny tricks and quirks that make the language that much more interesting.  I recently learned a nice fact about Object.create:  using null as the only argument to create an ultra-vanilla dictionary!

JavaScript或实际上是任何编程语言中最有趣的部分之一是,大量的小技巧和怪癖使该语言变得更加有趣。 我最近了解到一个关于Object.create的好事实:使用null作为创建超香草词典的唯一参数!

Object.create has been an awesome utility for prototype creation.  While that's nice, objects created with Object.create have __proto__ and inherited Object properties which can be manipulated.  What if you simply want a dictionary not prone to manipulation from the outside?  You can have that with Object.create(null):

Object.create是用于原型创建的强大工具。 很好,但是使用Object.create创建的对象具有__proto__和可以操纵的继承的Object属性。 如果您只是希望字典不易于受到外界的操纵该怎么办? 您可以使用Object.create(null)


let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them


Since there's no prototype your Object can't be manipulated from the outside -- it remains as vanilla of a dictionary as possible!  Compare that to Object.create({}):

由于没有原型,因此无法从外部操纵您的Object,它仍然尽可能地像字典一样! 将其与Object.create({})进行比较:


let obj = Object.create({});

// obj.__proto__ === {}
// obj.hasOwnProperty === function

Object.prototype.someFunction = () => {};

// obj.someFunction === () => {};
// dict.someFunction === undefined


Passing Object.create an empty object allows for properties to be added via Object.prototype.customPropName, something you may not always want.

传递Object.create一个空对象允许通过Object.prototype.customPropName添加属性,而您可能并不总是希望这样。

I hadn't known of this trick until recently but will be using it quite a bit going forward!

直到最近我才知道这个技巧,但是以后会用到很多!

翻译自: https://davidwalsh.name/object-create-null

object.create

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值