将Function.prototype.bind压缩为140个字符

时间:2016-07-15 21:38:28

标签: javascript ecmascript-6

这是来自MDN的绑定polyfill函数:

Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
        // closest thing possible to the ECMAScript 5
        // internal IsCallable function
        throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP = function() {},
        fBound = function() {
            return fToBind.apply(this instanceof fNOP ? this : oThis,
                aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    if (this.prototype) {
        // Function.prototype doesn't have a prototype property
        fNOP.prototype = this.prototype;
    }
    fBound.prototype = new fNOP();

    return fBound;
};

我想使用ES2015语法将其压缩为140个字符或更少。

以下是否实现了相同的目标(虽然不是Function.prototype上的方法)?

var bind=(f,t,...a)=>{
 function g(...b){
   return f.call(this instanceof g?this:t,...a,...b)
 }
 g.prototype=Object.create(f.prototype||{});
 return g
}

我对instanceof检查是否相同感兴趣。

编辑:g已转换为非箭头功能(如果删除了空格,则会将字符数限制为一个字符)

1 个答案:

答案 0 :(得分:0)

你的ES6语法更好

绑定Shim缩小其161

var bound1 = myFunction.bind(arg1, arg2, arg3);

Function.prototype.bind=function(d){
     var s=Array.prototype.splice,
         a=s.call(arguments,1),
         c=this;

     return function(){
         return c.apply(d,a.concat(s.call(arguments,0)))
     }
 }

绑定实用程序功能103

var bound2 = bind(myFunction, [arg1, arg2, arg3]);

function bind(f,a) {
     return function(){
         return f.call(a.concat(Array.prototype.splice.all(arguments,0)));
     }
}
相关问题