I'm trying to use some of the more advanced OO features of Javascript, following Doug Crawford's "super constructor" pattern. However, I don't know how to set and get types from my objects using Javascript's native type system. Here's how I have it now:
function createBicycle(tires) {
var that = {};
that.tires = tires;
that.toString = function () {
return 'Bicycle with ' + tires + ' tires.';
}
}
How can I set or retrieve the type of my new object? I don't want to create a type
attribute if there's a right way to do it.
The
instanceof
operator, internally, after both operand values are gather, uses the abstract[[HasInstance]](V)
operation, which relies on the prototype chain.The pattern you posted, consists simply on augmenting objects, and the prototype chain is not used at all.
If you really want to use the
instanceof
operator, you can combine another Crockford's technique, Prototypal Inheritance with super constructors, basically to inherit from theBicycle.prototype
, even if it's an empty object, only to foolinstanceof
:A more in-depth article:
if you're using a constructor, a better solution than instanceOf, would be this :
The explanation of WHY it's the best way to do it relies in This post.
If you declare
Bicycle
like this,instanceof
will work:In Firefox only, you can use the
__proto__
property to replace the prototype for an object. Otherwise, you cannot change the type of an object that has already been created, you must create a new object using thenew
keyword.I believe the quote above was written by Douglas Crockford.