javascript name of object function

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

提交回复
热议问题