Search code examples
javascriptcreatejs

How to print object name in CreateJS


var stage = new createjs.Stage("demoCanvas");
console.log(stage.constructor.name);//prints a
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
 <canvas id="demoCanvas" width="500" height="300">
        alternate content
 </canvas>

I am trying to print the constructor name in create js but it is printing a.Is there any solution to print constructor name.


Solution

  • CreateJS is minified. That means that a lot of the variable names of things not directly accessible have been shortened in order to make the code smaller. Check out this simplified example.

    let a = function(){}
    
    let Closure = {
      MyClass : a
    }
    
    let myInstance = new Closure.MyClass(); 
    
    console.log(myInstance.constructor.name) // a

    If you were to only look at the last two lines you would expect that the constructor of Closure.MyClass would be MyClass, but as you can see the constructor is actually a since that's the name of the constructor function that Closure.MyClass mentions.

    Maybe you should rethink the way you're using/creating the objects. If you have the ability to, then attach the name yourself either in the constructor of the object or after the object is created and reference that name.

    let a = function(){ this.name = "MyClass" }
    
    let Closure = {
      MyClass : a
    }
    
    let myInstance = new Closure.MyClass(); 
    
    myInstance.name2 = "MyClass"; // alternative method
    
    console.log(myInstance.name) // MyClass
    console.log(myInstance.name2) // MyClass

    There's also other ways you might be able to accomplish what you want, you might have to get creative. Or you could try using the un-minified version of the library.