您现在的位置是:网站首页 > 函数属性和方法文章详情

函数属性和方法

在JavaScript中,函数是一等公民,既可作为值传递,也能拥有属性和方法。函数本身是对象,因此能够动态扩展功能,甚至改变行为。以下是函数的核心属性和方法详解。

函数的属性

name 属性

函数的name属性返回函数声明时的名称,匿名函数或箭头函数会根据上下文推断名称。

function greet() {}
console.log(greet.name); // "greet"

const sayHi = function() {};
console.log(sayHi.name); // "sayHi"

const arrow = () => {};
console.log(arrow.name); // "arrow"

length 属性

length属性表示函数定义时的形参数量,不包含默认参数或剩余参数。

function sum(a, b, c = 10) {}
console.log(sum.length); // 2

const restParams = (...args) => {};
console.log(restParams.length); // 0

prototype 属性

构造函数通过prototype属性实现原型继承。非构造函数(如箭头函数)没有此属性。

function Person(name) {
  this.name = name;
}
Person.prototype.sayName = function() {
  console.log(this.name);
};
const p = new Person('Alice');
p.sayName(); // "Alice"

const arrowFn = () => {};
console.log(arrowFn.prototype); // undefined

函数的方法

call() 和 apply()

显式绑定this并立即执行函数。call()接受参数列表,apply()接受参数数组。

const user = { name: 'Bob' };
function showMessage(age, city) {
  console.log(`${this.name}, ${age}, ${city}`);
}

showMessage.call(user, 30, 'New York'); // "Bob, 30, New York"
showMessage.apply(user, [30, 'New York']); // 同上

bind()

创建新函数并永久绑定this和部分参数(柯里化)。

const boundFn = showMessage.bind(user, 30);
boundFn('Paris'); // "Bob, 30, Paris"

toString()

返回函数源码字符串,包括注释和空格。

function example() {
  // 这是一个示例
  return 'Hello';
}
console.log(example.toString());
// 输出完整函数定义(含注释)

自定义属性

函数作为对象可动态添加属性,常用于缓存或状态跟踪。

function counter() {
  counter.count = (counter.count || 0) + 1;
  return counter.count;
}
console.log(counter()); // 1
console.log(counter()); // 2

高阶函数特性

函数组合

通过属性存储中间函数实现管道操作。

function double(x) { return x * 2; }
function square(x) { return x ** 2; }

function compose(...fns) {
  return fns.reduce((f, g) => (...args) => f(g(...args)));
}

const transform = compose(double, square);
console.log(transform(5)); // 50 (先平方后翻倍)

元编程相关

new.target

检测函数是否通过new调用,用于区分构造调用与普通调用。

function Foo() {
  if (!new.target) throw '必须使用new调用';
  this.created = true;
}
new Foo(); // 正常
Foo(); // 抛出错误

Symbol.hasInstance

自定义instanceof操作符行为。

class MyArray {
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance);
  }
}
console.log([] instanceof MyArray); // true

我的名片

网名:~川~

岗位:console.log 调试员

坐标:重庆市-九龙坡区

邮箱:cc@qdcc.cn

沙漏人生

站点信息

  • 建站时间:2013/03/16
  • 本站运行
  • 文章数量
  • 总访问量
微信公众号
每次关注
都是向财富自由迈进的一步