defineProperty创建的属性

defineProperty创建的属性

本文介绍了如何使用GCC重命名Object.defineProperty创建的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在ADVANCED_OPTIMIZATIONS模式下重命名对象属性.

I wish to rename object property in ADVANCED_OPTIMIZATIONS mode.

优化前的代码:

/**
 * @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 not renamed the property name - "items".

推荐答案

正如@owler正确回答的那样,Closure-compiler无法重命名Object.defineProperty创建的属性,因为它们总是被引用.相反,请使用Object.defineProperties,因为它们可以带引号也可以不带引号.

As @owler correctly answered, Closure-compiler can not rename Object.defineProperty created properties because they are always quoted. Instead, use Object.defineProperties as they may be either quoted or unquoted.

/**
 * @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定义的属性不适合基于类型的重命名,因此,仅当未在externs集合中的任何类型上定义该属性时,才会重命名.这样,我的示例将items属性替换为items$.

Note: Properties defined via Object.defineProperties are not eligible for type-based renaming and as such will only be renamed if the property is not defined on any type in the externs set. As such, my example replaces the items property with items$.

这篇关于如何使用GCC重命名Object.defineProperty创建的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:18