LoginSignup
0
0

More than 5 years have passed since last update.

[クイズ]javascriptと仲良くなるための一歩 第25話「関数で不変オブジェクト 注意2」

Posted at

問題

function MyClass() {}
MyClass.prototype.x = 1;
var obj = new MyClass();

obj.x                //=> 1
obj.x = 10;
obj.x;               //=> 10
Object.freeze(obj);
obj.x = 100
obj.x                //=> ?

var obj2 = new MyClass();
obj2.x               //=> 1
obj2.x = 10;
obj2.x               //=> ?

: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:

答え

  • プロトタイプ継承元も不変にしたければ、継承元に対して明示的に行う必要がある
function MyClass() {}
MyClass.prototype.x = 1;
var obj = new MyClass();

obj.x                //=> 1
obj.x = 10;
obj.x;               //=> 10
Object.freeze(obj);
obj.x = 100
obj.x                //=> 10

var obj2 = new MyClass();
obj2.x               //=> 1
obj2.x = 10;
obj2.x               //=> 10
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