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
还没有评论,来说两句吧...