<script>
function foo(p1,p2) {
this.val = p1 + p2;
}
var bar = foo.bind(this, "p1");
//bar = fToBind.apply(this instanceof fNOP &&
//oThis ? this : oThis || window,
//aArgs.concat(Array.prototype.slice.call(arguments)));
var baz = new bar("p2");//(柯里化)new
console.log(baz.val);//p1p2
if (!Function.prototype.bind) {//为了判断浏览器是否支持bind()函数
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {//因为call和apply的存在,可以将this指向其他对象,如foo.bind.call(obj),就是为了防止此情况的出现
throw new TypeError('调用者不是当前函数对象');
}
var aArgs = Array.prototype.slice.call(arguments, 1);//从传进的参数中截取第一个(this)参数后面的参数
fToBind = this,
fNOP = function () { },//这个的作用相当于事例对象的构造函数,because
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis || window,//&&优先级高于?: 这里的this指向的是fBound
aArgs.concat(Array.prototype.slice.call(arguments)));
};
//this instanceof fNOP判断fNOP是否是this的构造函数,是为了确保是在原对象的基础上继续添加的参数
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
</script>