Search code examples
javascriptfunctiondynamicpseudo-class

How to set a dynamically generated pseudoclass name in JavaScript to work with the instanceof operator?


I'd like to set the name of a JavaScript pseudoclass stored in an array with a specific name, for example, the non-array version works flawlessly:

var Working = new Array();
Working = new Function('arg', 'this.Arg = arg;');
Working.prototype.constructor = Working;
var instw = new Working('test');
document.write(instw.Arg);
document.write('<BR />');
document.write((instw instanceof Working).toString());

Output:

test
true

However this format does not function:

// desired name of pseudoclass
var oname = 'Obj';

var objs = new Array();
objs.push(new Function('arg', 'this.Arg = arg;'));

// set objs[0] name - DOESN'T WORK
objs[0].prototype.constructor = oname;

// create new instance of objs[0] - works
var inst = new objs[0]('test');
document.write(inst.Arg);

document.write('<BR />Redundant: ');
// check inst name - this one doesn't need to work
try { document.write((inst instanceof objs[0]).toString()); } catch (ex) { document.write('false'); }
document.write('<BR />Required: ');
// check inst name - this is the desired use of instanceof
try { document.write((inst instanceof Obj).toString()); } catch (ex) { document.write('false'); }

Output:

test
Redundant: true
Required: false

Link to JSFiddle.


Solution

  • You've got a couple of things going on here that are a little bit off-kilter in terms of JS fluency (that's okay, my C# is pretty hackneyed as soon as I leave the base language features of 4.0).

    First, might I suggest avoiding document.write at all costs?
    There are technical reasons for it, and browsers try hard to circumvent them these days, but it's still about as bad an idea as to put alert() everywhere (including iterations).
    And we all know how annoying Windows system-message pop-ups can be.

    If you're in Chrome, hit CTRL+Shift+J and you'll get a handy console, which you can console.log() results into (even objects/arrays/functions), which will return traversable nodes for data-set/DOM objects and strings for other types (like functions). One of the best features of JS these days is the fact that your IDE is sitting in your browser.
    Writing from scratch and saving .js files isn't particularly simple from the console, but testing/debugging couldn't be any easier.

    Now, onto the real issues.

    Look at what you're doing with example #1. The rewriting of .prototype.constructor should be wholly unnecessary, unless there are some edge-case browsers/engines out there.

    Inside of any function used as a constructor (ie: called with new), the function is basically creating a new object {}, assigning it to this, setting this.__proto__ = arguments.callee.prototype, and setting this.__proto__.constructor = arguments.callee, where arguments.callee === function.

    var Working = function () {};
    var working = new Working();
    console.log(working instanceof Working); // [log:] true
    

    Working isn't a string: you've make it a function.
    Actually, in JS, it's also a property of window (in the browser, that is).

    window.Working    === Working;  // true
    window["Working"] === Working; // true
    

    That last one is really the key to solving the dilemma in example #2.

    Just before looking at #2, though, a caveat:
    If you're doing heavy pseud-subclassing,

    var Shape = function () {
        this.get_area = function () { };
    },
    
    Square = function (w) {
        this.w = w;
        Shape.call(this);
    };
    

    If you want your instanceof to work with both Square and Shape, then you have to start playing with prototypes and/or constructors, depending on what, exactly, you'd like to inherit and how.

    var Shape = function () {};
    Shape.prototype.getArea = function () { return this.length * this.width; };
    
    var Square = function (l) { this.length = l; this.width = l; };
    Square.prototype = new Shape();
    
    var Circle = function (r) { this.radius = r; };
    
    Circle.prototype = new Shape();
    Circle.prototype.getArea = function () { return 2 * Math.PI * this.radius; };
    
    var circle = new Circle(4),
        square = new Square(4);
    
    circle instanceof Shape; // true
    square instanceof Shape; // true
    

    This is simply because we're setting the prototype object (reused by every single instance) to a brand-new instance of the parent-class. We could even share that single-instance among all child-classes.

    var shape = new Shape();
    Circle.prototype = shape;
    Square.prototype = shape;
    

    ...just don't override .getArea, because prototypical-inheritance is like inheriting public-static methods.

    shape, of course, has shape.__proto__.constructor === Shape, much as square.__proto__.constructor === Square. Doing an instanceof just recurses up through the __proto__ links, checking to see if the functions match the one given.

    And if you're building functions in the fashion listed above (Circle.prototype = new Shape(); Circle.prototype.getArea = function () { /* overriding Shape().getArea() */};, then circle instanceof Circle && circle instanceof Shape will take care of itself.

    Mix-in inheritance, or pseudo-constructors (which return objects which aren't this, etc) require constructor mangling, to get those checks to work.

    ...anyway... On to #2:

    Knowing all of the above, this should be pretty quick to fix.

    You're creating a string for the desired name of a function, rather than creating a function, itself, and there is no Obj variable defined, so you're getting a "Reference Error": instead, make your "desired-name" a property of an object.

    var classes = {},
        class_name = "Circle",
    
        constructors = [];
    
    
    classes[class_name] = function (r) { this.radius = r; };
    
    constructors.push(classes.Circle);
    
    var circle = new constructors[0](8);
    circle instanceof classes.Circle;
    

    Now everything is nicely defined, you're not overwriting anything you don't need to overwrite, you can still subclass and override members of the .prototype, and you can still do instanceof in a procedural way (assigning data.name as a property of an object, and setting its value to new Function(data.args, data.constructor), and using that object-property for lookups).

    Hope any/all of this helps.