reflect.apply 是 es6 反射 api,用于以指定 this 值和参数数组调用函数,语法更语义化、校验更严格;若 target 非函数,直接抛明确 typeerror,优于传统 func.apply 的隐式报错。

Reflect.apply 是 ES6 提供的反射 API 方法,专门用于**以指定 this 值和参数列表调用函数**,功能等价于 Function.prototype.apply,但语法更语义化、更安全(不会因非函数对象报错,而是返回 TypeError)。
基本用法:传入函数、this 值和参数数组
语法:Reflect.apply(target, thisArgument, argumentsList)
-
target:必须是可调用函数,否则抛
TypeError -
thisArgument:函数执行时绑定的
this值(可为任意类型,包括null、undefined) - argumentsList:必须是类数组或数组,元素将作为实参依次传入函数
对比传统 apply,更安全的调用方式
传统写法:func.apply(obj, [a, b, c])
用 Reflect.apply 等效写法:Reflect.apply(func, obj, [a, b, c])
优势在于:
- 如果 func 不是函数,func.apply(...) 会直接报错(TypeError: func.apply is not a function);
- 而 Reflect.apply(func, ...) 会在第一步就校验 target 类型,错误信息更明确(TypeError: CreateListFromArrayLike called on non-object 或类似),便于调试。
实际使用示例
假设有一个方法依赖 this 访问实例属性:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
const user = {
name: 'Alice',
greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
};
用 Reflect.apply 调用并绑定 this:
const result = Reflect.apply(user.greet, user, ['Hello', '!']); console.log(result); // "Hello, Alice!"
也可用于绑定 null 或原始值(非严格模式下会被自动包装):
Reflect.apply(function() { return this; }, 'hello', []); // String {'hello'}
配合 Proxy 或高阶函数的典型场景
比如在 Proxy 的 apply 拦截器中,常需原样转发调用:
const handler = {
apply(target, thisArg, args) {
console.log('函数被调用,this:', thisArg);
return Reflect.apply(target, thisArg, args); // 安全转发
}
};
const proxyFn = new Proxy(myFunc, handler);
或封装一个带日志的通用调用器:
function loggedApply(fn, thisVal, args) {
console.log(`Calling ${fn.name || 'anonymous'} with this=${thisVal}`);
return Reflect.apply(fn, thisVal, args);
}
不复杂但容易忽略:它不改变函数本身,只是提供一种更规范、更可控的动态调用方式。只要确保 target 是函数、argumentsList 可遍历,就能可靠传 this 并执行。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










