写一个bind方法

作者: 打不过就加入他 | 来源:发表于2016-09-23 23:37 被阅读700次

对bind,apply,call的用发理解还不够深刻。

手写一个bind方法

//context为需要被绑定上的对象,arguments是参数
Function.prototype.bind = function(context){
  var self = this; //this => Function
  return function(){
      return self.apply(context,arguments)
  }
}

再复杂一点

//context为需要被绑定上的对象,arguments是参数
Function.prototype.bind = function(){
  var self = this; //this => Function
  var context = [].shift.call(arguments); //arguments 的第一个为需要绑定的this上下文
  var args = [].slice.call(arguments)// arguments除了第一个,成为一个数组
  return function(){
      return self.apply(context,[].concat.call(args,[].slice.call(arguments)))
  }
}
//运行
var obj = {name: 'shaojingjing'}
var func = function(a,b,c,d){
  alert(this.name); // shaojingjing
  alert([a,b,c,d]) // [1,2,3,44]
}.bind(obj,1,2).(3,4)

相关文章

  • 写一个bind方法

    对bind,apply,call的用发理解还不够深刻。 手写一个bind方法 再复杂一点

  • JS中bind()

    Function.prototype.bind() 一. 什么是bind()方法? bind()方法创建了一个新的...

  • 分析 MDN bind方法的Polyfill

    一、bind 方法介绍 bind 方法创建一个新的绑定函数 bind 方法重新绑定原函数的 this 值 在调用绑...

  • 前端面试宝典之:手写bind方法

    手动实现一个 bind 方法 bind 方法简介 在正式手写之前,你得知道 bind 方法是一个什么东西,在 MD...

  • javascript bind 方法封装

    javascript bind 方法封装 Function.prototype.bind方法非常强大,可以绑定一个...

  • JS-手动实现bind、call方法

    实现bind方法 MDN文档指出:bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 t...

  • 基础-bind方法及实现原理

    1. bind方法 函数调用bind方法, 可以指定函数内部的this, 并把bind函数的第一个参数之后的参数拼...

  • js的bind方法实现

    bind方法介绍 bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行...

  • 手写bind

    手写bind bind语法 bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为...

  • bind, call, apply all about 'thi

    bind: bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被bind的第一个参数指...

网友评论

    本文标题:写一个bind方法

    本文链接:https://www.haomeiwen.com/subject/pwqxyttx.html