Escape Javascript Syntax

Topics: General
Mar 19, 2013 at 4:27 AM
Is there a way to flag or make a particular snippet of code to be ignored or compiled as is? Basically I want to access the "name" property of the "constructor" function. So in this instance "this.constructor" gives me a "The property 'constructor' does not exist on value of type 'MyType'".

Of course that's totally valid error in typescript but it's valid javascript. I thought maybe ambients would help somehow but I couldn't figure it out. I've got a workaround where I declare a static method on a helper class that gets me what I want but still, for academic purposes...
module CustomUI {
    export class Control {        
        toString() {
            // alert(this.constructor.name);        // throws error.
            CustomUI.ControlHelper.className(this);
        }
    }

    export class ControlHelper {
        static className(obj) {
            alert(obj.constructor.name);
        }
    }
}
Mar 19, 2013 at 9:54 AM
It should have been possible to do the following:
toString() {
  alert((<Object>this).constructor.name);
}
But it looks like the constructor property is missing from the definition for Object - a bug IMO.

A workaround is to access the property dynamically:
toString() {
  alert(this["constructor"].name);
}
But then one loses compile-time safety.
Mar 19, 2013 at 5:06 PM
Thanks, I had tried a cast and it didn't work so I thought I was missing something but you're right, the code complete shows other object members, just not constructor, or for that matter any of the proto members (like "proto").

Ramblings =>

In my real implementation I recursively dig through each level of the prototype chain until I reach Object, appending the name to a string so that I end up with something like Object.Control.UI.Button (AssignedID).

It certainly seems that constructor should be a member of Object, however maybe the idea is that by hiding constructor it makes it harder for someone to manually invoked the function. Not that it would typically have any affect with the way the javascript is generated from the typescript. Meh, I'm just thinking about why it might be hidden on purpose.