如何使用 GCC 重命名 Object.defineProperty 创建的 属性

How to rename property created by Object.defineProperty with GCC

我想在 ADVANCED_OPTIMIZATIONS 模式下重命名对象 属性。

优化前的代码:

/**
 * @constructor
 */
function Container() {
  var items = [];
  Object.defineProperty(this, 'items', {
    set: function(value) {
      items = value;
    },
    get: function() {
      return items;
    }
  });
}

var container = new Container();
container.items = [1,2,3];
console.log(container.items);

优化后:

var b = new function() {
  var a = [];
  Object.defineProperty(this, "items", {set:function(c) {
    a = c
  }, get:function() {
    return a
  }})
};
b.e = [1, 2, 3];
console.log(b.e);

Closure Compiler 未重命名 属性 名称 - "items".

Closure Compiler 不会重命名曾用引号字符串引用的属性:

Whenever possible, use dot-syntax property names rather than quoted strings. Use quoted string property names only when you don't want Closure Compiler to rename a property at all.

https://developers.google.com/closure/compiler/docs/api-tutorial3#enable-ui

因为 Object.defineProperty 需要一个字符串作为 属性 名称,我猜没有办法让 Closure Compiler 重命名它。如果您真的需要这个,您可以在 Closure Compiler Forum 上询问是否有某种方法可以诱使编译器这样做。

正如@owler 正确回答的那样,Closure 编译器无法重命名 Object.defineProperty 创建的属性,因为它们总是被引用。相反,请使用 Object.defineProperties,因为它们可能被引用或未被引用。

/**
 * @constructor
 */
function Container() {
  var items = [];

  Object.defineProperties(this, {
    items$: {
      set: function(value) {
        items = value;
      },
      get: function() {
        return items;
      }
    }
  });
}

var container = new Container();
container.items$ = [1,2,3];
console.log(container.items$);

注意:通过 Object.defineProperties 定义的属性不符合基于类型的重命名条件,因此只有在 属性 未在任何类型上定义时才会重命名外部设置。因此,我的示例将 items 属性 替换为 items$.