简体   繁体   English

方法preventExtensions javascript和defineProperty

[英]method preventExtensions javascript and defineProperty

First of all Hello to everyone, and sorry for my English. 首先,大家好,对不起我的英语。
I would still take advantage of the expertise and availability of this community. 我仍然会利用这个社区的专业知识和可用性。
My question is realted to try to add properties to an object after preventExtensions method. 我的问题已经解决,尝试在preventExtensions方法之后向对象添加属性。
I know how this method works, this method makes an object not extensible, i can not add any property to this object 我知道此方法的工作原理,该方法使对象不可扩展,我无法向该对象添加任何属性
My question is: why if i try to add a property in this way (obj.prop), i'll find no errors in console and this property will be undefinded, 我的问题是:为什么如果我尝试以这种方式添加属性(obj.prop),则控制台中不会发现任何错误,并且该属性将无法定义,
but if i try to add a new property with Object.defineproperty method i'll find an error in console? 但是,如果我尝试使用Object.defineproperty方法添加新属性,则会在控制台中发现错误?

<script>
       var obj={}
       Object.preventExtensions(obj)
       // i can not add other properies to this object
       console.log(Object.isExtensible(obj))//false

       // why if i try to add a property in this way i'll find undefined
       obj.b='bbb'
       console.log(obj.b)

       // and in this way i'll find an error
       Object.defineProperty(obj, 'w', { enumerable: true,configurable:true,writable:true,value:'www' });
</script>

Basically my question is about the different behavior between obj.prop and Object.defineProperty 基本上我的问题是关于obj.prop和Object.defineProperty之间的不同行为
Any suggestions will be read with pleasure, thank you all. 任何建议都会很高兴地阅读,谢谢大家。

I imagine this behavior is browser specific. 我想这种行为是特定于浏览器的。 Even the documentation seems to be vague on the topic. 甚至文档也对此主题含糊不清。

Attempting to add new properties to a non-extensible object will fail, either silently or by throwing a TypeError (most commonly, but not exclusively, when in strict mode). 尝试将新属性添加到不可扩展的对象将失败, 无论是无提示还是通过抛出TypeError (在严格模式下,这都是最常见的,但不是排他的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM