let obj = { age:26, } function Person(name, sex) { console.log(this); console.log(this.age); console.log(name, sex); } Function.prototype.bindToApply = function(context){ let _self = this, _slice = Array.prototype.slice,
tFun = function(){}; let args = _slice.call(arguments, 1); let fn = function(){ let allArgs = _slice.call(arguments); _self.apply(this instanceof _self ? this : context, args.concat(allArgs)); } tFun.prototype = _self.prototype;
fn.prototype = new tFun(); return fn; } // 测试一 // Person.bind(obj, "测试")("男"); // Person.bindToApply(obj, "测试")("男"); // 测试二 // let obj2 = Person.bindToApply(obj, "测试"); // new obj2(‘男‘); // let obj2 = Person.bind(obj, "张三"); // new obj2(‘男‘);
以上代码是用的apply重写的bind方法:call与apply的区别只在于传参方式不同
call方法:Person.call(obj, "测试","男");
apply方法:Person.apply(obj, ["测试","男"]);
bind方法:Person.bind(obj, ["测试","男"])();
bind方法执行后 => Person.bind(obj, ["测试","男"]) 是返回的一个函数,而call与apply是直接返回结果的 所以bind方法后面是需要加上“()”执行括号的
tFun