我正在尝试创建一个函数,比如说:
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"
(当然这是一个例子)
有可能吗?
答案 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
修改
如果你想改变原型,可以这样做:
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