两种自定义实现bind()的方法比较

两种自定义实现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 的环境中使用类似功能,第二个实现可能是更好的选择。文中若有不足之处,欢迎留言指正。

  • 21
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
一、AspNetPager支持两种方式分页: 一种是PostBack方式分页, 一种是通过Url来实现分页以及Url重写功能 二、AspNetPager支持各种数据绑定控件GridView、DataGrid、DataList、Repeater以及自定义的数据绑定控件的分页功能十分强大。 三、AspNetPager分页控件本身并不显示任何数据,而只显示分页导航元素,数据在页面上的显示方式与该控件无关,所以需要手写数据连接方法来配合, 四、结合TOP 。。。NOT IN 的通用存储过程分页方法使用AspNetPager十分实用 测试控件datalist aspnetpager 的分页方法示例 分页方法为 PostBack 方式 1、 首先将AspNetPager.dll复制于应用程序下的bin目录,打开解决方案,引入dll文件 2、 在工具栏中添加控件,这样可以支持拖拽使用 3、 要使用AspNetPager 要为其设置最基本的属性 使用 SqlServer Northwind数据库的 Products表 protected Wuqi.Webdiyer.AspNetPager AspNetPager1; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.DataList DataList1; private void Page_Load(object sender, System.EventArgs e) { this.AspNetPager1.PageSize=10; //设置每也显示的记录条数 if(!IsPostBack) //只在页面第一次加载时起作用 { SqlDBManager db = new SqlDBManager(System.Configuration.ConfigurationSettings.AppSettings["SqlConnectionString"]); AspNetPager1.RecordCount=db.CountPage("products");//获得要使用表的记录总数 //db.CountItems自定义方法 this.BindData(); } } private void BindData() { SqlDBManager db= new SqlDBManager(System.Configuration.ConfigurationSettings.AppSettings["SqlConnectionString"].ToString(); DataList1.DataSource=db.FenPage(this.AspNetPager1.PageSize,this.AspNetPager1.CurrentPageIndex,"productid","products","productid,productname,unitprice,unitsinstock",""); //自定义方法由 TOP not in 存储过程分页方法改编 this.DataList1.DataBind(); //控件数据绑定 this.Label1.Text="当前第"+this.AspNetPager1.CurrentPageIndex+"页 总"+this.AspNetPager1.PageCount+"页"; } private void AspNetPager1_PageChanged(object sender, System.EventArgs e) { //页索引改变方法 this.BindData(); } 设计页效果 <asp:DataList id="DataList1" style="Z-INDEX: 101; LEFT: 296px; POSITION: absolute; TOP: 96px" runat="server"> <HeaderTemplate> <table border='1'> <tr> <td>产品ID</td> <td>产品名称</td> <td>产品数量</td> <td>产品单价</td> </tr> </HeaderTemplate> <FooterTemplate> </table> </FooterTemplate> <ItemTemplate> <tr> <td><%# DataBinder.Eval(Container.DataItem,"Productid")%></td> <td><%# DataBinder.Eval(Container.DataItem,"productname")%></td> <td><%# DataBinder.Eval(Container.DataItem,"unitprice")%></td> <td><%# DataBinder.Eval(Container.DataItem,"unitsinstock")%></td> </tr> </ItemTemplate> </asp:DataList> <webdiyer:AspNetPager id="AspNetPager1" style="Z-INDEX: 102; LEFT: 256px; POSITION: absolute; TOP: 40px" runat="server" Width="500px" FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PrevPageText="上一页" Height="40px" NumericButt PagingButt ShowNavigati ShowInputBox="Always" TextAfterInputBox="页" TextBeforeInputBox="跳转到第" AlwaysShow="True"> </webdiyer:AspNetPager> <asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 120px; POSITION: absolute; TOP: 56px" runat="server">Label</asp:Label>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值