简体   繁体   English

如何使用Google Closure编译器声明动态属性?

[英]How to declare dynamic properties with Google Closure Compiler?

/**
 * @param {Object} object
 * @param {(string|number)} name
 * @param {*} value
 */
var fabric = function(object, name, value) {
    object[name] = value;
};


fabric(Number, 'MAX_INTEGER', 9007199254740991);
// ...

console.log(Number.MAX_INTEGER); // 9007199254740991

WARNING: JSC_INEXISTENT_PROPERTY: Property MAX_INTEGER never defined on Number at line 14 character 12 警告:JSC_INEXISTENT_PROPERTY:属性MAX_INTEGER从未在第14行字符12的Number上定义

How to declare the dynamic properties without pre definitions? 如何在没有预定义的情况下声明动态属性?

UPD: UPD:

Number['MAX_INTEGER']; 数[ 'MAX_INTEGER'];

This falls under the Restrictions for ADVANCED_OPTIMIZATIONS of the documentation. 这属于文档的ADVANCED_OPTIMIZATIONS限制 You must consistently refer to properties using either the dotted notation or quoted syntax. 您必须使用点分符号或引用语法一致地引用属性。 When you mix access, the compiler may rename the dotted access, but will not touch the quoted syntax and thus generate incorrect code. 当您混合访问时,编译器可能会重命名点分访问,但不会触及引用的语法,因此会生成错误的代码。

If you do want to add properties in this way, you have two alternatives: 如果确实要以这种方式添加属性,则有两种选择:

add a stub declaration in your externs (which will prevent renaming): 在您的外部代码中添加一个存根声明(这将防止重命名):

/** @const {number} */
Number.MAX_INTEGER;

or use @lends with a object literal: 或将@lends与对象文字一起使用:

/**
 * @param {Object} object
 * @param {Object} props
 */
var fabric2 = function(object, props) {
  for (var prop in props) {
    object[prop] = props[prop];
  }
};

fabric2(Number, /** @lends {Number} */ { MAX_INTEGER: 9007199254740991 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM