简体   繁体   English

确定匿名函数的属性名称

[英]Determine the property name of an anonymous function

Is it possible to determine the property name of an anonymous function within the function? 是否可以在函数中确定匿名函数的属性名? For instance... 例如...

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Testing</title>  
        <script type="text/javascript">
            var $={};
            $.fn={};
            $.fn.somePropertyName = function() {
                console.log(this); // Object { somePropertyName=function()}
                //How do I get "somePropertyName" here?
            };
            $.fn.somePropertyName()
        </script>
    </head>

    <body></body> 
</html>

My purpose is so I don't need to type out "myPluginName" twice when creating jQuery plugins. 我的目的是使我在创建jQuery插件时无需两次键入“ myPluginName”。 Not that I am lazy, but don't want the chance of a difference. 并不是说我很懒,但是不希望有改变的机会。

$.fn.myPluginName= function(method) {
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method) {
        return methods.init.apply(this, arguments);
    } else {
        // Somehow get the property name "myPluginName" here.
        $.error('Method ' +  method + ' does not exist on jQuery.myPluginName');
    }    
};

You can write a routine which finds a particular function on an object, and returns the property key: 您可以编写一个例程来查找对象上的特定函数,然后返回属性键:

function find_fn(obj, fn) {
  let (var i in obj) if (obj[i] === fn) return i;
}

function name(fn) {
  return find_fn($.fn, fn);
}

Now use the trick of binding the function to itself, so the function can refer to itself from within itself using this : 现在,使用将函数绑定到自身的技巧,以便可以使用this从自身内部引用函数:

$.fn.foo = function() { console.log('my name is', name(this); }
$.fn.foo = $.fn.foo.bind($.fn.foo);
$.fn.foo();

However, it might be easier to simply do: 但是,简单地执行以下操作可能会更容易:

const FUNCNAME = 'somePropertyName';
$.fn[FUNCNAME] = function() {
  console.log("I am", FUNCNAME);
};

If you mistype FUNCNAME now, you'll get a ReferenceError or something. 如果您现在误输入FUNCNAME,则会收到ReferenceError或其他错误。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM