javascript name of object function

后端 未结 2 1384
耶瑟儿~
耶瑟儿~ 2020-12-22 12:33

Suppose I have an object like this:

var myObject = {};

myObject.myFunction = function() {
    var name = ; // name should be myFunct         


        
相关标签:
2条回答
  • 2020-12-22 13:21

    @Felix Kling's solution is awesome but it depends on the function expression being named. As he said if you ever need to know the name of the property to which an anonymous function is being assigned then your code design is bad. Nevertheless, if you want to write bad code then please write it like this instead:

    function anonymous(method) {
        return function () {
            var args = Array.prototype.slice.call(arguments), name = "";
    
            for (var key in this) {
                if (this[key] === method) {
                    name = key;
                    break;
                }
            }
    
            return method.apply(this, args.concat(name));
        };
    }
    

    Now you can create your anonymous functions like this:

    var myObject = {};
    
    myObject.myFunction = anonymous(function (name) {
        // function body
    });
    

    Remember that name must be the last argument of your function.

    0 讨论(0)
  • 2020-12-22 13:35

    There is no generic way to do this. If you call the function such that this refers to the object, you can iterate over the properties of the object and compare the values:

    myObject.myFunction = function() { 
        var name;
        var func = arguments.callee;
        for (var prop in this) {
            if (this[prop] === func) {
                name = prop;
                break;
            }
        }
    };
    

    Note that the usage of arguments.callee is deprecated in favor of named function expressions. That is, you should do:

    myObject.myFunction = function func() {  // <- named function expression
        var name;
        for (var prop in this) {
            if (this[prop] === func) {
                name = prop;
                break;
            }
        }
    };
    

    However, I wonder why you would need this. The property name should not have an impact on the inner workings of the function, and if it does, it seems to be badly designed IMO.

    0 讨论(0)
提交回复
热议问题