javascript高级进阶之bind原理

143 阅读1分钟
  • bind特点
  1. 改变this指向并传递参数给原有函数
  2. 返回一个绑定后的函数(高阶函数)
  3. 如果绑定的函数被new了,则当前函数this指向的是当前实例
  4. new出来的结果可以找到原有类的原型
  • bind实现

    var obj = { name: '猫' } function fn(type,age) { console.log(this) console.log(this.name+"是"+type+"今年"+age+"岁") } var bindFn = fn.bind(obj, '哺乳类'); bindFn(6);

结果:

模拟实现:

Function.prototype.bind = function(context){
    var that = this;
    //获取第一层函数的参数,将类数组arguments转为真正的数组
    var bindArg = [].slice.call(arguments, 1)
    function Fn() {}
    //返回一个函数
    function boundFn() {
     var args = [].slice.call(arguments, 0)
      
     //改变原有函数中的this指向,若是绑定函数被new了,则this指向当前函数实例
     return that.apply(this instanceof boundFn ? this : context,bindArg.concat(args))
    }
    Fn.prototype =this.prototype;
    boundFn.prototype = new Fn();
    //boundFn.prototype = this.prototype; //简单粗暴 将函数原型挂载在原函数原型上
    return boundFn;
}
 
 fn.prototype.age = '22'
//绑定的函数被new了
var instance = new bindFn(6)
console.log(instance.age) // 22

下集--new的实现原理。