Does it make sense to create immutable objects that share the structure using the javascript prototype system

So far, there seem to be two opposing immutability solutions in Javascript:

  • immutable.js
  • seamless

immutable.js introduces its (shallow) immutable objects, which are incompatible with standard javascript protocols for objects and arrays.

seamlessly immutable uses POJOs that are completely immutable without magic but without structural separation.

It would be great to combine the best of both worlds. Can the correct prototype chain / tree decisions be immutable?

The basic prototype mechanism gives hope:

var a = [1, 2, 3];
var b = Object.create(a);

b[0]; // 1
b.map(function (x) { return ++x; }); // 2, 3, 4 

b.push(4, 5, 6); // initial assignment of b
a; // 1, 2, 3
b;  // 1, 2, 3, 4, 5, 6

for (var i = 0; i < b.length; i++) {
  console.log(b[i]);
} // 1, 2, 3, 4, 5, 6

a[1] = null; // prototype mutation
a; // 1, null, 3
b; // 1, null, 3, 4, 5, 6

b.unshift(0); // instance mutation
a; // 1, null, 3
b; // 0, 1, null, 3, 4, 5, 6 !!!

, (unshift) (b) , js, , . , .

, /, :

var a = [1, 2, 3];
Object.freeze(a);
var b = Object.create(a);
b.push(4, 5, 6); // Error: Cannot assign to read only property "length"
Object.freeze(b);

: length , , . :

var b = Object.create(a, {length: {value: a.length, writable: true}});

, , , .

, - , .

Aadit , , .

+4
2

js, ,

, (shift, push ..) (, , .length, -). , , ( , , ).

,

/ ?

. , . , " " , "" , . (), , immutable.js . [[prototype]] - , .

0

:

  • .
  • ES5 [[DefineOwnProperty]]

- . , , . . , .

[[DefineOwnProperty]]. length :

function A() {}
A.prototype = Array.prototype;
var a = new A();

a[0] = 0, a[1] = 1;
console.log(a.length); // 0
a.length = 2;
console.log(a); // [0, 1]
a.length = 1;
console.log(a[1]); // 1

[] , , API . , , , , -. , . [/Opinion]

0

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


All Articles