在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ javascript如何取得函數(shù)或者變量的名稱?補(bǔ)充一下,需要兼容ie

javascript如何取得函數(shù)或者變量的名稱?補(bǔ)充一下,需要兼容ie

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>javascript如何取得函數(shù)或者變量的名稱</title>
</head>

<body>
    <script>       
        
        function test1 () {
            alert(1);
        }
        
        var test2 = function () {
            alert(2)
        };
        
        function getName (fn) {            
            var name = '';  // 想在這里得到傳過來的函數(shù)或變量名稱
            return name;
        }
        
        
        getName(test1)  // 想要的結(jié)果是: test1
        getName(test2)  // 想要的結(jié)果是: test2
        
    </script>
</body>
</html>
回答
編輯回答
青裙
2018年8月18日 14:05
編輯回答
安于心

Function.prototype.toString.call(function test(){}).match(/functions(1)(/)[1]
應(yīng)該能剛得住IE6


  1. ( ?
2018年7月19日 17:27
編輯回答
喜歡你

IE幾?
IE9+可以用這種方法

    if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s([^(]{1,})\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1].trim() : "";
        },
        set: function(value) {}
    });
}

2018年1月28日 23:42
編輯回答
淚染裳

兼容所有平臺,包括nodejs

function test1 () {}
function getFunctionName (fn) {
   const match = fn && fn.toString().match(/^\s*function (\w+)/)
   return match ? match[1] : ''
}
console.log(getFunctionName(test1)); // test1
2018年5月20日 21:03
編輯回答
別硬撐

感覺函數(shù)表達(dá)式?jīng)]法辦到。

假設(shè)有10個變量都引用了匿名函數(shù)f,那你豈不是希望能夠通過f獲得這10個變量名?

2018年3月28日 23:49
編輯回答
青黛色
    function getName (fn) {
        return fn.name;
    }
2018年4月30日 11:10