ryandlf
ryandlf

Reputation: 28555

Possible to Prototype ALL Objects

In javascript, is there a way to prototype all objects. A simple usecase would be, I have a function:

testFn(el) {
    if(el.isElement()) {
        //Do something
    }
}

Here I would like to test if the object passed into the function is a DOM element. Normally I would use this function:

function isElement(el) {
    if(typeof el == 'object' && 'nodeType' in el && el.nodeType === 1 && el.cloneNode) {
        return true;
    }
    return false;
}

However, I find myself rewriting this code over and over again. It would be nice if I could simply prototype Object and have this function available on the fly for every object, whenever I might need it. Prototyping Object seems to give me errors though.

Upvotes: 0

Views: 59

Answers (1)

Sarfraz
Sarfraz

Reputation: 382806

is there a way to prototype all objects

You can use prototype on Object:

Object.prototype.isElement = function () {
    return typeof this == 'object' && 'nodeType' in this && this.nodeType === 1 && this.cloneNode
}

Upvotes: 1

Related Questions