博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
手动实现bind函数(js)
阅读量:753 次
发布时间:2019-03-23

本文共 1273 字,大约阅读时间需要 4 分钟。

手动实现bind函数

⭐ 实现步骤

  1. 判断调用的对象是否是function
  2. 保存传入到调用的的函数(第一部分形参)
  3. 定义一个回调函数作为bind函数返回
  4. 定义的函数使用箭头,为了就是保存执行上下文中上文中的this,避免在定义该回调函数以后this指向改变了。当然除了使用箭头函数你也可以在回调函数之前保存this
  5. 因为返回回调函数之后,可能还有继续传入参数的,所以还要在保存一次与上述2中的arr做拼接。array.concat()就是实现数组拼接的方法之一
  6. 最后一步就是改变调用函数的this指向啦,并将mybound返回

⭐保存this的方法一

let self=this         var mybound=function (){
/* bind 的回调函数 (bind的执行返回的是一个函数) */ console.log(arguments,arr) arr=arr.concat(arguments)/* 与上一个splice 同样的效果 */ self.apply(context,arr) /* 使用apply 改变 调用bind函数的this指向 */ }

⭐原生bind

Function.prototype.mybind=function(context){
if(typeof this!=="function"){
/* 判断调用bind 是否是函数 */ throw new Error("this not a function") /* 抛出错误 直接在浏览器报错啦 */ } var arr=[].splice.call(arguments,1)/* 使用call捕获从第二个开始传入的参数 */ //使用箭头函数避免this指向改变 var mybound=()=>{
/* bind 的回调函数 (bind的执行返回的是一个函数) */ // console.log(arguments,arr) arr=arr.concat(arguments)/* 与上一个splice 同样的效果 */ this.apply(context,arr) /* 使用apply 改变 调用bind函数的this指向 */ } return mybound } var obj={
name:"lijia" } function foo(age,pp){
console.log(this.name,age,pp) } foo.mybind(obj,20,30)()

转载地址:http://cfizk.baihongyu.com/

你可能感兴趣的文章