7

Suppose there is a global variable which is a function

function MyClass(){}

and there are methods of this class such as

MyClass.func1 = function()
{
}

I want to ensure that YUI compression and obfuscation works without putting entire class inside a closure like

(function () {
    function MyClass(){}
    MyClass.func1 = function()
    {
    }
})();

Is there a way to make YUI compression work without doing this?

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I am afraid that YUI compression ignores global variables, any particular reason why u want class to be global? Reference link http://alistapart.com/article/javascript-minification-part-II – Raunak Kathuria Apr 21 '15 at 06:50
  • @RaunakKathuria Yes, One because it is an existing product, and also because keeping the class global ensures that only one instance can be created of that class. – gurvinder372 Apr 21 '15 at 10:40
  • 2
    keeping the class global has nothing to do with the number of instance that can result... – dandavis Apr 23 '15 at 07:11
  • If what you need is a single instance you should use the singleton pattern. Making your class global does not automatically gives you that. – devconcept Apr 24 '15 at 12:25
  • @dandavis No, it doesn't. But by keeping a class global I meant that reference to the class is global. Means that a developer doesn't have to create an instance of the class by doing new className(); – gurvinder372 Apr 27 '15 at 09:42

1 Answers1

2

Well, I suppose you could wrap it in an anonymous function before compressing it, and then just remove the anonymous function after.

Also make sure you're using prototype ;)

(function () {
  function MyClass(){}
  MyClass.prototype.func1 = function()
  {
  }
})();

Results in:

(function(){function a(){}a.prototype.func1=function(){}})();

And just take out the anonymous function:

function a(){}a.prototype.func1=function(){}
John Harding
  • 432
  • 1
  • 6
  • 14
  • I am not using prototype, and it is too much of a change at this point in time. Is there a way to do it without using prototype? – gurvinder372 May 05 '15 at 13:11
  • Well, prototype is useful for creating instances of an object. It can still be used in the way you are, but new instances of MyClass won't have access to MyClass.func1. [See here](http://stackoverflow.com/questions/9582341/adding-new-properties-to-constructor-function-without-prototype) – John Harding May 05 '15 at 22:55