实现简易版js bind

bind()方法会创建一个新函数。当这个新函数被调用时,bind()的第一个参数将作为它运行时的 this, 之后的一序列参数将会在传递的实参前传入作为它的参数。
bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

Function.prototype.bound = function(){
    arguments = Array.prototype.slice.call(arguments);
    var BoundThis = arguments[0];
    var BoundArg = arguments.slice(1);
    var fn =this;
    return function(){
        fn.apply(BoundThis,BoundArg.concat(Array.prototype.slice.call(arguments)));
    }
}

var thisObj = {name:"heh555eh"};

function a() {
    console.log(this.name);
    console.dir(arguments);
}

var b = a.bound(thisObj,1);

console.dir(b);

b(3,4);

猜你喜欢

转载自blog.csdn.net/blueblueuueew/article/details/70227090