简体   繁体   English

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

[英]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

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 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何声明一个可以在express js中的任何视图调用的函数? - How to declare a function that can be called from any view in express js? 未从对象内部调用函数 - function not called from within object 我该如何解决从函数内部调用函数的元素? - How can I address the element that called a function from within the function? 我可以在PHP中声明对象并将其传递给函数吗? - Can I declare and pass an object to a function in PHP? 任何方式我都可以声明事件 object 而不是在 function 的参数中? - Any way I can declare the event object rather than in the params of a function? JavaScript:是否可以通过查询调用哪个函数来声明变量? (新手) - JavaScript: Can I declare a variable by querying which function is called? (Newbie) 将函数/属性注入另一个函数/对象,可以从该 function 中的函数调用或读取/设置? - Inject a function/property to another function/object that can be called or read/set from functions within that function? 在Javascript中,如何从该函数中调用但在其他位置定义的函数中引用函数范围的变量? - In Javascript, how can I reference a function-scoped variable from a function called within that function but defined elsewhere? 在另一个函数中调用时从函数返回的未定义对象 - Undefined object returned from function when called within another function 我怎么能在javascript中声明这个对象? - How could i declare this object in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM