dev.pus
dev.pus

Reputation: 8139

How to check inheritance (object/prototype of)

I have want to check if an object extends another object (true, false):

Example:

var BaseObject = function(object) {
    this.name = object.name;
    this.someFunction = object.someFunction;
    this.someOtherProperty = object.someOtherProperty;
};

var ExtendingObject = new BaseObject({
    name: "extention",
    someFunction: function(value) { return value; },
    someOtherProperty = "hi"
});

// some possible function
var extends = isExtending(BaseObject, ExtendingObject);
var isParentof = isParentOf(BaseObject, ExtendingObject);

Does underscore.js provide such a function (well I found none...)?

How can I perform such a check?

Upvotes: 3

Views: 10610

Answers (3)

Mitya
Mitya

Reputation: 34556

ExtendingObject (no reason to capitalise it, by the way - it's not a class) is not really extending the base object in the traditional sense - it is merely instantiating it.

For this reason, as @Inkbug says (+1), if you want to ensure that ExtendingObject is an instance of the base object, you can use

alert(ExtendingObject instanceof BaseObject); //true

Note that instanceof can answer only the question "is A an instance of B" - you cannot ask it "what is A an instance of?".

For the latter, you could do something like (though I don't think this is cross-browser)

alert(ExtendingObject.constructor.name); //"BaseObject"

Upvotes: 3

Inkbug
Inkbug

Reputation: 1692

Try using the instanceof operator.

Upvotes: 7

BigBoss
BigBoss

Reputation: 6914

I don't know about underscore.js but instanceof work for your need. You can use it this way:

function Unrelated() {}
function Base( name, fn, prop ) {
   this.name = name;
   this.someFunction = fn;
   this.someProperty = prop;
}
function Extending( name, fn, prop, newProp ) {
   Base( name, fn, prop );
   this.newProperty = prop;
}
Extending.prototype = new Base();
var a = new Extending( 'name', function () {}, 'prop', 'newProp' );

and now you can say:

if( a instanceof Extending ) {/*it is true because a.prototype = Extending*/}
if( a instanceof Base ) {/*it is true because a.prototype.prototype = Base*/}
if( a instanceof Unrelated ) {/*it is false since Unrelated is not in prototype chain of a*/}

Upvotes: 1

Related Questions