码迷,mamicode.com
首页 > 其他好文 > 详细

Function.prototype.bind 简介

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

标签:bin   prototype   bar   code   logs   use   nbsp   问题:   rip   

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 简介

标签:bin   prototype   bar   code   logs   use   nbsp   问题:   rip   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!