在 JavaScript 中,Function 是一种特殊的对象类型,因此函数也拥有自己的方法和属性。这些方法和属性可以分为以下两类:
1. Function 对象的实例方法
这些方法可以直接通过函数实例调用。
-
apply(thisArg, argsArray)- 调用函数,并指定
this值和参数数组。 - 示例:
function greet(greeting, name) { console.log(`${greeting}, ${name}`); } greet.apply(null, ['Hello', 'Alice']); // "Hello, Alice"
- 调用函数,并指定
-
call(thisArg, ...args)- 调用函数,并指定
this值和参数列表。 - 示例:
function greet(greeting, name) { console.log(`${greeting}, ${name}`); } greet.call(null, 'Hello', 'Alice'); // "Hello, Alice"
- 调用函数,并指定
-
bind(thisArg, ...args)- 返回一个新函数,并将
this绑定到指定的值,同时可以预设部分参数。 - 示例:
function greet(greeting, name) { console.log(`${greeting}, ${name}`); } const sayHelloToAlice = greet.bind(null, 'Hello', 'Alice'); sayHelloToAlice(); // "Hello, Alice"
- 返回一个新函数,并将
-
toString()- 返回函数的字符串表示(通常是函数的源代码)。
- 示例:
function greet() { console.log('Hello'); } console.log(greet.toString()); // "function greet() { console.log('Hello'); }"
-
length- 返回函数定义时的形参个数(不包括剩余参数和默认值参数)。
- 示例:
function add(a, b) {} console.log(add.length); // 2
2. Function 对象的静态方法
这些方法直接作用于 Function 构造函数。
-
Function.prototype- 所有函数共享的原型对象,允许扩展函数的共有行为。
- 示例:
Function.prototype.describe = function () { console.log(`This function has ${this.length} parameters.`); }; function test(a, b) {} test.describe(); // "This function has 2 parameters."
-
Function构造函数- 可以动态创建函数(不推荐,容易导致安全和性能问题)。
- 示例:
const sum = new Function('a', 'b', 'return a + b'); console.log(sum(1, 2)); // 3
Function 对象的原有属性
除了方法,函数对象还具有以下属性:
-
name- 返回函数的名称(匿名函数返回空字符串)。
- 示例:
function greet() {} console.log(greet.name); // "greet" const anon = function () {}; console.log(anon.name); // ""
-
prototype- 每个函数(构造函数)都有一个
prototype属性,指向其原型对象。 - 示例:
function Person() {} console.log(Person.prototype); // {}
- 每个函数(构造函数)都有一个
-
constructor- 返回创建对象的构造函数的引用。
- 示例:
function Test() {} const instance = new Test(); console.log(instance.constructor === Test); // true
总结
- 实例方法:
apply、call、bind、toString。 - 静态方法:
Function构造函数、Function.prototype。 - 属性:
length、name、prototype、constructor。
这些方法和属性是 Function 对象的基础功能,广泛用于函数调用、上下文绑定和动态行为扩展。
481

被折叠的 条评论
为什么被折叠?



