LoginSignup
0
0

More than 5 years have passed since last update.

[クイズ]javascriptと仲良くなるための一歩 第19話「プロパティ属性」

Last updated at Posted at 2017-08-06

問題

var a = {x:2, y:3}
var b = {x:2, y:3}
var c = {x:1, y:2}
JSON.stringify(a)                      //=> "{"x":2,"y":3}"
JSON.stringify(a) == JSON.stringify(b) //=> true
JSON.stringify(a) == JSON.stringify(c) //=> false

var obj = Object.create(
            Object.prototype,
            {
               x: {value:2, writable:true, enumerable:true, configurable:true},
               y: {value:3, writable:true, enumerable:true, configurable:true}
            }
          );
JSON.stringify(a) == JSON.stringify(obj) //=> ?

:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:
:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:

答え

JSON.stringify(a) == JSON.stringify(obj) //=> true

プロパティ属性を明示的に示しているだけなのでtrueになります。
また、
obj.xをwritable:falseにしてJSON.stringify(a) == JSON.stringify(obj)しても、JSON.stringify()では出力に違いが出ないので、trueになります。

プロパティ属性のチェックはObject.getOwnPropertyDescriptor(obj, prop)で、できます。

obj = { x:2, y:3 }
Object.getOwnPropertyDescriptor(obj, 'x') //=> Object {value: 2, writable: true, enumerable: true, configurable: true}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0