[英]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 ? 有可能吗?
You can use call
, and change the function a little bit otherwise it will return "object" for most checks: 您可以使用
call
,并稍微更改功能,否则对于大多数检查,它将返回“ object”:
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.