es3的语法来模拟es5的bind方法

        // 简单版
        Function.prototype.bind = function(context) {
            var self = this;
            return function() {
                self.apply(context, arguments);
            };
        };
        // 稍微复杂那么一丢丢的bind版
        Function.prototype.bind = function() {
            var self = this,    // 原函数
                context = [].shift.call(arguments),    // this要绑定的上下文环境
                args = [].slice.call(arguments);    // 剩余参数
            return function() {
                return self.apply(context, [].concat.call(args, [].slice.call(arguments)));    // 使用apply绑定context, 参数也组合好了传入原函数
            };
        };

        var obj = {
            name: 'Sorrow.X'
        };

        function fn(a, b, c, d) {
            console.log(this.name);
            console.log(a, b, c, d);
        };

        fn.bind(obj, 1, 2)(3, 4);

 

posted @ 2017-07-03 11:00  Sorrow.X  阅读(366)  评论(0编辑  收藏  举报