Javascript 编程基础(4)函数 | 4.4、bind() 方法
文章目录
- 一、`bind()` 方法
- 1、概述
- 2、核心特性
- 2.1、永久 `this` 绑定
- 2.2、参数预设
- 2.3、构造函数兼容性
- 3、工作原理
- 4、常见问题
一、bind()
方法
1、概述
bind()
是 JavaScript 函数对象的一个内置方法,它创建一个新的函数(称为"绑定函数"),这个新函数的this
值会被永久绑定到指定的对象。与call()
和apply()
不同,bind()
不会立即执行函数,而是返回一个准备就绪的新函数。基本语法,如下:
const boundFunc = originalFunc.bind(thisArg[, arg1[, arg2[, ...]]])
2、核心特性
2.1、永久 this
绑定
bind()
创建的绑定函数会永久锁定this
值,即使使用call()
或apply()
也无法改变:
const obj = { value: 42 };
function getValue() { return this.value; }const boundGetValue = getValue.bind(obj);
console.log(boundGetValue()); // 42
console.log(boundGetValue.call({ value: 100 })); // 仍然是 42
2.2、参数预设
bind()
可以预先设置函数的部分参数:
function greet(greeting, name) {console.log(`${greeting}, ${name}!`);
}// 预设第一个参数
const sayHello = greet.bind(null, "Hello");
sayHello("Alice"); // 输出: "Hello, Alice!"// 预设多个参数
const sayHiToBob = greet.bind(null, "Hi", "Bob");
sayHiToBob(); // 输出: "Hi, Bob!"
2.3、构造函数兼容性
当绑定函数被用作构造函数时(使用
new
调用),原始this
绑定会被忽略:
function Person(name) {this.name = name;
}const BoundPerson = Person.bind({ x: 1 });
const p = new BoundPerson('Alice');
console.log(p.name); // "Alice" (不是 {x:1})
3、工作原理
JavaScript 引擎处理
bind()
时大致执行以下步骤:
- 创建一个新函数对象
- 将原函数的代码复制到新函数
- 设置新函数的内部
[[BoundThis]]
属性为指定的thisArg
- 将
bind()
的其他参数存储为[[BoundArgs]]
- 返回这个新函数
当调用绑定函数时:
- 创建一个新的执行上下文
- 将
this
设置为[[BoundThis]]
的值 - 将
[[BoundArgs]]
和调用时传入的参数合并 - 执行原函数的代码
4、常见问题
问题1:为什么箭头函数不需要 bind
?
箭头函数没有自己的
this
,它会捕获所在上下文的this
值,且无法通过bind
改变。
问题2:bind()
和 call()
/apply()
的主要区别是什么?
bind()
返回一个新函数而不立即执行,且this
绑定是永久的;call()/apply()
立即执行函数且只影响当前调用。
问题3:能否对同一个函数多次 bind
?
可以,但只有第一次
bind
有效,后续bind
无法覆盖已绑定的this
值。