object.create_Object.create(空)

Love The Way You Lie 2023-02-22 01:18 72阅读 0赞

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)

  1. let dict = Object.create(null);
  2. // dict.__proto__ === "undefined"
  3. // 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({})进行比较:

  1. let obj = Object.create({});
  2. // obj.__proto__ === {}
  3. // obj.hasOwnProperty === function
  4. Object.prototype.someFunction = () => {};
  5. // obj.someFunction === () => {};
  6. // 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 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读

    相关 字符串

    空字符串 1. 空字符串 字符串常量的书写方式是用一对双引号包围一串字符,如下所示: “Hello” “\aWarning!\a” “L