我可以声明一个可以在任何对象中调用的函数吗?

时间:2015-11-28 14:34:59

标签: javascript

我正在尝试创建一个函数,比如说:

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

我想对任何类型的任何变量进行强制转换

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"

(当然这是一个例子)

有可能吗?

1 个答案:

答案 0 :(得分:2)

您可以使用call,稍微更改一下这个功能,否则会返回“对象”进行大多数检查:

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

修改

如果你想改变原型,可以这样做:

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