当定义和调用函数时,JavaScript 函数对象会自动具有一些特定的属性,以下是一些常见的属性和方法。

1. arguments : arguments 是一个类数组对象,它包含了函数调用时传递的参数。它允许你在函数内部访问传递给函数的参数列表,即使在函数定义时未明确声明这些参数。可以通过索引访问 arguments 对象中的参数值,也可以使用 arguments.length 获取传递的参数个数。

function exampleFunc(a, b) {
    console.log(arguments[0]); // 访问第一个参数
    console.log(arguments.length); // 参数的个数
}

exampleFunc(1, 2, 3); // 1,3

注意:在es6开始,推荐使用剩余参数或者使用命名参数来代替使用 arguments 对象。

 

 

2. length : length 属性返回函数声明时的形参数量,即函数期望接收的参数个数。它表示函数定义时定义的形参个数,不包括剩余参数。

function exampleFunc(a, b, c) {
    // 函数体
}

console.log(exampleFunc.length); // 3

 

 

3. name : name 属性返回函数的名称。对于具名函数,它返回函数的实际名称。

function namedFunction() {
// 函数体
}

const anonymousFunction = function() {
// 函数体
}

console.log(namedFunction.name); // namedFunction
console.log(anonymousFunction.name); // anonymousFunction

 

这些属性使得函数对象在运行时具有额外的元数据,可以根据需要访问这些属性来获取有关函数的信息,例如函数的参数、参数个数和名称。这些属性在编写灵活和通用的函数时非常有用。

 

 

4. caller : caller 属性返回一个调用当前函数的函数引用。如果当前函数是在全局作用域中被调用的,那么 caller 将返回 null 。该属性在严格模式下被禁用。

function outerFunc() {
    innerFunc();
}

function innerFunc() {
    console.log(innerFunc.caller); // outerFunc
}

outerFunc();

 

 

5. prototype : prototype 属性允许你向函数对象添加新的属性和方法。它用于创建基于原型继承的对象。

function Person(name) {
    this.name = name;
}

Person.prototype.sayHello = function() {
    console.log("Hello, " + this.name);
};

const person = new Person("John");
person.sayHello(); // Hello, John

 

 

6. bind() : bind() 方法返回一个新的函数,该函数在调用时将指定的 this 值绑定到提供的参数,用于创建函数的新实例并永久性地绑定函数的上下文。

const obj = {
    name: "John",
    greet: function() {
        console.log("Hello, " + this.name);
    }
};

const boundFunc = obj.greet.bind(obj);
boundFunc(); // Hello, John

类似的还有 apply() 、 call() 、 toString() 等。

 

 

7. constructor : constructor 属性返回创建函数对象的原型对象的引用。

function Person(name) {
    this.name = name;
}

const person = new Person("John");

console.log(person.constructor); // 输出:Person

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/ronaldo9ph/p/17414005.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程