Frage

Lets say we have a poll of objects with a function of objects something like below and I want to call each fn using something like _.invoke. We can do this easily before gcc advanced minimization via _.invoke(pool, "fn"), no problem. However, after minifcation fn may be c or some other property name... Is there anyway to hint to gcc that a string is referencing a property name? I want it to update my invoke call to _.invoke(pool, "c") after it's done minifying the code.

For a reproducible example of the problem try running gcc with advanced compilation on this script:

// ==ClosureCompiler==
// @externs_url http://cdn.jsdelivr.net/g/underscorejs
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
var pool = [{fn: function() {}, prop2: 1}, {fn: function() {}, prop2: 2}, {fn: function() {}, prop2: 3}]
_.invoke(pool, "fn");

Which produces obviously not equivalent code:

_.invoke([{a:function(){},b:1},{a:function(){},b:2},{a:function(){},b:3}],"fn");

I'm hoping the resulting compiled code will be

_.invoke([{a:function(){},b:1},{a:function(){},b:2},{a:function(){},b:3}],"a");
War es hilfreich?

Lösung

There are several ways:

1) Quote the original property definition:

{"fn": ...}

2) Provide a definition in a extern file:

/** @type {Object} */
var methods;
methods.fn;

3) Use the magic "JSCompiler_renameProperty" method:

_.invoke(pool, JSCompiler_renameProperty("fn"));

This isn't used much (so has a higher chance of being flaky) and isn't recommended with type based optimizations. Note that you have a provide a stub implementation like:

function JSCompiler_renameProperty(a) { return a; }

If you want the code to function uncompiled or compile without warnings.

Andere Tipps

Just quote the property names you don't want gcc to rename:

var pool = [{"fn": function() {}, "prop2": 1}, {"fn": fun ...

See also: inconsistent property names

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top