两种自定义实现bind()的方法比较
文章目录
前言
自定义bind两种实现的优劣比较。
一、bind()是什么?
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called。
bind()方法创建一个新函数,当调用该函数时,将其this关键字设置为所提供的值,并在调用新函数时提供的任何参数之前设置给定的参数序列。
二、js原生bind()使用
原生 JavaScript 的 Function.prototype.bind() 方法通常用于确保函数在被调用时拥有特定的 this 值,并且可以在调用时预置一些参数。以下是一些使用 bind() 方法的常见场景:
1.确保事件处理函数中的 this 指向正确
在处理 DOM 事件时,事件处理函数中的 this 通常指向触发事件的元素,而不是我们期望的上下文对象。使用 bind() 可以解决这个问题。
代码如下(示例):
function MyComponent() {
this.button = document.getElementById('my-button');
this.handleClick = this.handleClick.bind(this);
this.button.addEventListener('click', this.handleClick);
}
MyComponent.prototype.handleClick = function() {
console.log(this); // 正确指向 MyComponent 实例
};
var component = new MyComponent();
2. 定制化函数参数
使用 bind() 来创建一个新函数,该函数在调用时已经有了一些预设的参数。
代码如下(示例):
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 创建一个新函数,它总是将 'a' 作为第一个参数
var leadingThirtysevenList = list.bind(null, 'a');
var list2 = leadingThirtysevenList(); // ['a']
var list3 = leadingThirtysevenList(1, 2, 3); // ['a', 1, 2, 3]
3. 回调函数中的 this 绑定
在异步回调函数中,this 的值可能不是期望的。使用 bind() 可以确保回调函数中 this 的正确指向。
代码如下(示例):
function User(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.greet = function() {
setTimeout(function() {
console.log('Hello, my name is ' + this.firstName + ' ' + this.lastName);
}.bind(this), 1000);
};
}
var user = new User('John', 'Doe');
user.greet(); // 一秒后输出: Hello, my name is John Doe
4. 绑定构造函数
虽然不推荐使用 bind() 绑定构造函数,因为 new 操作符的行为可能与预期不符,但在某些特殊情况下,它仍然可以被用作一种技巧。
代码如下(示例):
function MyConstructor() {
this.value = 'hello';
}
var obj = {};
var boundConstructor = MyConstructor.bind(obj);
boundConstructor();
console.log(obj.value); // 输出 'hello'
- 请注意,在使用 bind() 时,你需要确保原始函数不会改变其 this 绑定的逻辑,因为这可能会导致不可预测的行为。
三、自定义bind()
1、简易版
代码如下(示例):
if (!Function.prototype.bind) {
Function.prototype.bind1 = function(context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var innerArgs = Array.prototype.slice.call(arguments);
return self.apply(context, args.concat(innerArgs));
};
};
}
优点:
1、简洁性:这个实现相对简单和直接,容易理解。
2、功能性:它确实实现了基本的 bind 功能,即在给定上下文中调用函数,并将预先指定的参数与调用时提供的参数合并。
缺点:
1、原型链问题:这个实现没有处理原型链的继承,即函数没有 self 函数的原型链。这可能导致函数调用无法正确继承 self 的方法。
2、new 运算符:如果函数使用 new 运算符来调用,那么 context 将被忽略,因为 this 关键字在构造函数中通常指向新创建的对象实例。
2、完整版
代码如下(示例):
Function.prototype.bind2 = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fbound = function () {
self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
}
fNOP.prototype = this.prototype;
fbound.prototype = new fNOP();
return fbound;
}
优点:
1、原型链处理:这个实现通过创建一个空的辅助函数 fNOP 并设置其原型为 self 的原型,然后让 fbound 的原型成为 fNOP 的新实例,确保了 fbound 函数可以正确继承 self 函数的原型链。
2、new 运算符处理:在函数中使用了 this instanceof self ? this : context,这意味着如果函数作为构造函数使用(通过 new 调用),那么 this(即新创建的对象)将作为 self 的上下文,而不是预先指定的 context。
缺点:
复杂性:与第一个实现相比,这个实现更复杂,因为它处理了原型链继承和 new 运算符的特殊情况。
总结
总的来说,第二个实现提供了更完整和健壮的 bind 函数模拟,因为它考虑了原型链继承和 new 运算符的使用情况。而第一个实现虽然简单,但可能在某些场景下无法正确工作。在实际应用中,通常会使用 JavaScript 内置的 Function.prototype.bind 方法,因为它已经过优化并且内置在语言中。如果需要在不支持 bind 的环境中使用类似功能,第二个实现可能是更好的选择。文中若有不足之处,欢迎留言指正。