0

I am using gulp and gulp-uglify to minify my javascript code.

Gulp

var uglify= require('gulp-uglify');
gulp.task('javascript', function() {
    return gulp.src('./scripts/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('./'));
});

Original javascript

var Site = Site || {};
Site.Code = {
    obj: new ThirdPartyObject(),
    init: function() {
        obj.thirdPartyMethod();
    }
};

Minified javascript

var Site = Site || {};
Site.Code = {obj: new ThirdPartyObject,init: function() {
    obj.thirdPartyMethod()
}};

The minifier is removing the parentheses for obj: new ThirdPartyObject and therefore my code breaks when I make the call obj.thirPartyMethod().

How can I fix this?

psmears
  • 26,070
  • 4
  • 40
  • 48
christo8989
  • 6,442
  • 5
  • 37
  • 43

2 Answers2

6

The minifier is correct new X() and new X are equivalent.

Your code however, is not as correct. Here is the correct version:

var Site = Site || {};
Site.Code = {
    obj: new ThirdPartyObject(),
    init: function() {
        Site.Code.obj.thirdPartyMethod(); // <-- obj didn't exist
        // this.obj.thirdPartyMethod(); <-- also works, because this will be Site.Code when invoking Site.Code.init()
    }
};
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Tibos
  • 27,507
  • 4
  • 50
  • 64
0

Uglify is correct here. See new MyObject(); vs new MyObject; on StackOverflow.

new ThirdPartyObject; is a correct statement as a special case of new when applied to a constructor that takes no arguments.

Your call obj.thirdPartyMethod() is likely failing for other reasons. Are you sure obj is correctly resolved at the scope in which the init function is called? Do you need a this., or a reference to Site.Code?

Community
  • 1
  • 1
EyasSH
  • 3,679
  • 22
  • 36