Function.prototype.bind 简介

bind可以解决两种问题:

1. 可以改变一个函数的 this 指向

2. 可以实现偏函数等高阶功能

本文暂且讨论第一个功能

 

USE CASE

var foo = {
    x: 3
}

var bar = function(){
    console.log(this.x);
}

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3

 

简易版实现方式

Function.prototype.bind = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope);
    };
}

 

 

参考链接:https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/

posted @ 2017-04-21 13:57  savokiss  阅读(143)  评论(0编辑  收藏  举报