简体   繁体   中英

Can a pattern with getters and setters be avoided and still minify JavaScript with Closure ADVANCED_OPTIMIZATIONS?

I would like to minify JavaScript using the Closure Compiler in ADVANCED_OPTIMIZATIONS mode. This is a pattern that I'm currently trying out:

var myClosure = (function () {
    var NS = {};
    NS.foo = 100;
    var MyConstructor = function (aValue) {
        this.aValue = aValue;
    };
    NS["MyConstructor"] = MyConstructor;

    MyConstructor.prototype.setAValue = function (v) {
        this.aValue = v;
    };
    NS["MyConstructor"].prototype["setAValue"] = MyConstructor.prototype.setAValue;

    MyConstructor.prototype.readAValue = function () {
        return this.aValue;
    };
    NS["MyConstructor"].prototype["readAValue"] = MyConstructor.prototype.readAValue;

    return NS;
}());
window["myClosure"] = myClosure;

It works fine and I can call into the minified code with this:

var obj = new myClosure.MyConstructor(10);
alert(obj.readAValue());
obj.setAValue(100);
alert(obj.readAValue());

A JSFiddle to demonstrate.

While the above works, it will be very cumbersome to write all the getters and setters that this project will need in order to be able to call into the compiled code.

Is there a pattern that I can use that will allow me to avoid using getter / setter methods?

Or, if not, is there a way for me to judge if refactoring the code to get it to be callable with ADVANCED_OPTIMIZATIONS is going to be worth the effort. (I estimate that adding the methods will add over 5% in terms of number of lines to the uncompiled code) Also, I currently have about 1,300 QUnit assertion tests. To run these tests, there are close to 10,000 assignments made that will have to be rewritten from something like:

obj.ValueA = 100;
obj.ValueB = 200;

to

obj.SetValueA(100);
obj.SetValueB(200);

in order to test the minified code.

So, if possible, a different approach is definitely in order.

@expose was created for just this purpose.

/** @expose */
MyConstructor.prototype.aValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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