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 themSince 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 === undefinedPassing 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