首页 > 其他 > 详细

Function.prototype.bind 简介

时间:2017-04-21 14:27:43      阅读:218      评论:0      收藏:0      [点我收藏+]

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/

Function.prototype.bind 简介

原文:http://www.cnblogs.com/savokiss/p/6743282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!