Assign a new property to an empty object that has frozen the prototype

Why can't I assign new properties to an unfrozen object that froze the prototype:

Work without Object.freeze:

'use strict'
//This object will be prototype of next objects
var defaults = {
  name: 'def name', 
  sections: {
    1: {
      secName: 'def sec name'
    }
  }
};

//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);


specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true

specificObject.sections['1'] = Object.create(defaults.sections['1']);

The code works as expected, but I want to make sure that the default values ​​are not accidentally changed. So I want to freeze the default object:

'use strict'
//This object will be prototype of next objects
var defaults = {
  name: 'def name', 
  sections: {
    1: {
      secName: 'def sec name'
    }
  }
};

//!!!!!!!!!!!!
Object.freeze(defaults);

//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);

//TypeError: Cannot assign to read only property 'sections' of #<Object>
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true

specificObject.sections['1'] = Object.create(defaults.sections['1']);

What can't I do, why can't I assign a specificObject if its prototype is frozen?

// EDIT: Note that a specific object is not frozen:

'use strict'
//This object will be prototype of next objects
var protoObj = {a: 1, o: {}};
Object.freeze(protoObj);

console.log(Object.isFrozen(protoObj)); //true

var n = Object.create(protoObj);
console.log(Object.isFrozen(n)); //false
+1
source share
2 answers

I don’t understand why I can’t prescribe specificObjectif its prototype is frozen?

. , .

, [[writable]] false.

, , - . , , , ( ).

?

  • Object.defineProperty ,
  • , Object.create
  • defaults , specificObject.
0

, specificObject.sections , defaults, . {}, defaults.sections. specificObject.sections .

ownProperty specificObject, :

'use strict'
//This object will be prototype of next objects
var defaults = {
  name: 'def name',
  sections: {
    1: {
      secName: 'def sec name'
    }
  }
};

//!!!!!!!!!!!!
Object.freeze(defaults);

//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);

// this will create new property
Object.defineProperty(specificObject, 'sections',{
    enumerable: true,
    writable: true,
    configurable: true,
    value: {}
});
console.log(specificObject.hasOwnProperty('sections')); //true

specificObject.sections['1'] = Object.create(defaults.sections['1']);

:

obj.prop = val, javascript obj , , obj. , / val . , obj . prop prototype, obj val.

, prop , , . , .:)

EDIT:

@KubaWyrostek specificObj.sections = {}, , , , , , . .

0

Source: https://habr.com/ru/post/1627145/