3

Here's something interesting: In any JS window run:

val = document.body.getBoundingClientRect();
console.log(val)
val.left += 10;
console.log(val)

or any other modification to the return value. How is this object be immutable?

This makes it hard to duck-punch the getBoundingClientRect() for an element, changing the original values. Although I suppose you could recreate the object, I didn't know JS even had the capability of immutable objects. Is this correct?

NoBugs
  • 9,310
  • 13
  • 80
  • 146

1 Answers1

2

Just a simple example:

var getBoundingNothing = {left:20};
Object.freeze( getBoundingNothing );        // if you comment this line...

var gbn = getBoundingNothing;
console.log( gbn ); //  Object { left=20 }
gbn.left = 70 ;
console.log( gbn ); //  Object { left=20 }  // ...than left=70

consider reading this interesting article: http://ejohn.org/blog/ecmascript-5-objects-and-properties/

and from that article, all you need, head right to MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Am I correct in thinking there's no way to polyfill this? – Chris Hayes Nov 29 '14 at 09:29
  • @ChrisHayes see this: http://javascript.crockford.com/private.html Seems an obvious way. If Object.freeze is missing - you can prototype it creating closures and return immutable values. – Roko C. Buljan Nov 29 '14 at 09:45
  • That's an easy way to get immutability, but it's not really the same thing. I can't apply that to arbitrary objects, after all, and the overhead of setting up a prototype is much higher than just calling `Object.freeze`. [This question](http://stackoverflow.com/questions/13117771/javascript-object-doesnt-support-method-freeze) suggests a method, but it doesn't seem fully compatible with older browsers. I suppose it's a pipe dream to have it available in all browsers. – Chris Hayes Nov 29 '14 at 09:50
  • @ChrisHayes I don't think it's a good example that one, cause it uses the same methods introduced in ECMAScript 5 which leads to our dear .freeze – Roko C. Buljan Nov 29 '14 at 09:53
  • Yes, that's certainly a problem. I suppose it's useful if you're working with the odd browser that chose to implement everything *except* `freeze`. :) – Chris Hayes Nov 29 '14 at 09:53
  • @ChrisHayes By "odd browser" you mean IE8 or older? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#Browser_compatibility – NoBugs Nov 29 '14 at 15:17
  • @NoBugs IE8 doesn't appear to implement all of the ES5 methods necessary to do a shim for `Object.freeze`. – Chris Hayes Nov 29 '14 at 22:13