Mouradif
Mouradif

Reputation: 2704

Can i declare a function that could be called from within any object?

I'm trying to create a function, say :

function logType()
{
    console.log(typeof (this))
}

that I would like to cast on any variable of any type

var a = function() { return 1; }
var b = 4;
var c = "hello"

a.logType() // logs in console : "function"
b.logType() // logs in console : "number"
c.logType() // logs in console : "string"

(of course it's an example)

Is it possible in any way ?

Upvotes: 0

Views: 50

Answers (1)

Andy
Andy

Reputation: 63524

You can use call, and change the function a little bit otherwise it will return "object" for most checks:

function logType() {
    var type = ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
    console.log(type);
}

var a = function() { return 1; }
var b = 4;
var c = "hello"

logType.call(a) // function
logType.call(b) // number
logType.call(c) // string

DEMO

EDIT

If you want to change the prototype you can do something like this:

if (!('logType' in Object.prototype)) {
    Object.defineProperty(Object.prototype, 'logType', {
        value: function () {
            var type = ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
            console.log(type);
        }
    });
}

a.logType() // function
b.logType() // number
c.logType() // string

DEMO

Upvotes: 2

Related Questions