0

I put the following code into closure compiler on advanced mode:

var obj = (function() {
  /** @constructor */
  function H(a) {
    this.a = a
  }
  var h = new H(1);
  h.b=1
  return h
})();

The result I get back is:

(function() {
  var a = new function() {
  }(1);
  a.a = 1;
  return a;
})();

Why is it ignoring the change I make to the object h.b=1 ?

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • 1
    Try adding `this.b = null` in the constructor. Perhaps it's optimized in a way to ignore code that would result in multiple hidden classes? – plalx Sep 02 '14 at 17:41
  • @plalx I was hoping to see it add `this.b=1` to the constructor. – qwertymk Sep 02 '14 at 17:46
  • While the question by itself is valid, notice that [this pattern shouldn't be used](http://stackoverflow.com/q/10406552/1048572) – Bergi Sep 02 '14 at 18:41

1 Answers1

1

The advanced compilation options enable aggressive property removal, which includes some assumptions:

It makes a strong assumption that properties defined on a "prototype" or "this" will not be iterated over and thus is a candidate for removal.

/** @constructor */ function cls() { this.x = 1; // removal candidate due to "this" assumption; }

So what you're seeing is actually this.a = a being removed, and then the property b is being renamed to a.

lantius
  • 1,196
  • 9
  • 9