在JavaScript中,可以通过以下方法获取函数:
通过名称
使用 `window[name]` 语法,其中 `name` 是函数名。这种方法简单易用,但仅限于在全局作用域中查找函数名。
```javascript
function myFunction() {
// 函数体
}
const myFunctionRef = window['myFunction'];
```
通过引用
使用 `Function.prototype.bind()` 方法获取函数引用,再通过该引用调用函数。这种方法更加灵活,可以用于任何函数。
```javascript
function myFunction() {
// 函数体
}
const myFunctionRef = myFunction.bind(this);
```
获取函数名称
可以使用以下方法获取函数的名称:
Function.prototype.getName():
```javascript
Function.prototype.getName = function() {
return this.name || this.toString().match(/function\s+(\w+)/);
};
function myFunction() {
// 函数体
}
console.log(myFunction.getName()); // 输出 "myFunction"
```
通过 `arguments.callee`:
```javascript
function getFnName(callee) {
var _callee = callee.toString().replace(/[\s\?]*/g, "");
var re = /function\s+(\w+)/ig;
var matches = re.exec(_callee);
return matches ? matches : "anonymous";
}
function myFunction() {
// 函数体
}
console.log(getFnName(myFunction)); // 输出 "myFunction"
```
通过正则表达式:
```javascript
function getFunctionNames(fn) {
var fnStr = fn.toString();
var re = /function\s+(\w+)/ig;
var matches = [];
while ((matches = re.exec(fnStr)) !== null) {
matches.push(matches);
}
return matches;
}
function myFunction() {
// 函数体
}
console.log(getFunctionNames(myFunction)); // 输出 ["myFunction"]
```
选择哪种方法取决于具体需求。如果需要简单快速地获取函数名称,可以使用 `window[name]` 或 `Function.prototype.getName()`。如果需要更灵活的函数引用,可以使用 `Function.prototype.bind()`。如果需要获取多个函数的名称,可以使用 `getFunctionNames()` 方法。