简体   繁体   中英

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. 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 :

$.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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