Skip to content Skip to sidebar Skip to footer

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(); Workin

Solution 1:

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.

varWorking = function () {};
var working = newWorking();
console.log(working instanceofWorking); // [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;  // truewindow["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,

varShape = 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.

varShape = function () {};
Shape.prototype.getArea = function () { returnthis.length * this.width; };

varSquare = function (l) { this.length = l; this.width = l; };
Square.prototype = newShape();

varCircle = function (r) { this.radius = r; };

Circle.prototype = newShape();
Circle.prototype.getArea = function () { return2 * Math.PI * this.radius; };

var circle = newCircle(4),
    square = newSquare(4);

circle instanceofShape; // true
square instanceofShape; // 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 = newShape();
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.

Post a Comment for "How To Set A Dynamically Generated Pseudoclass Name In Javascript To Work With The Instanceof Operator?"