javascript name of object function

后端 未结 2 1395
耶瑟儿~
耶瑟儿~ 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.

提交回复
热议问题