如何检测函数是否已位于具有相同名称的函数中

How to detect that a function is already inside a function having that same name

本文关键字:函数 于具 何检测 检测 是否      更新时间:2023-09-26

我想做这样的事情;问题是(typeof myfunc == 'function')总是正确的,因为它是相同的函数名称。是否可以以某种方式将该自名函数排除在类型范围之外?

function myfunc() { 
    alert('old');       
}
function myfunc() { 
    if (typeof myfunc == 'function') {      
        // alert('old');        
        alert('new');
    } else {
        alert('myfunc does not exist');
    }
}

你试图做的事情是不可能的。在覆盖函数之前,您需要先捕获该函数。

var _orgFnc = window.myfunc;  //assuming it is global
function myfunc() { 
    if (_orgFnc) {      
        // alert('old');        
        alert('new');
    } else {
        alert('myfunc does not exist');
    }
}

如果它不是全局的,你基本上需要做

var _orgFnc = (typeof myfunc === "function") ? myfunc : null;

考虑一下

function myfunc() { } // first definition
function myfunc() { } // second definition

本质上与

var myfunc;
myfunc = (function() { }); // first definition
myfunc = (function() { }); // second definition

您可以在此处看到名称myfunc存在并引用函数对象。 第一个定义不再存在,因为第二个定义已经取代了它。

我认为,最接近的方法是在(重新)定义函数之前使用函数表达式并测试是否存在。

var myfunc;
myfunc = (function() { });
if (typeof myfunc === 'function') { 
    alert("Function exists"); 
} else {
    alert("Did not exist, create (new) definition now");
    myfunc = (function() { });
}