/** * 手写bind函数 * bind返回fun的拷贝,并指定了fun的this指向,保存了fun的参数 * 说白就是bind返回一个函数,函数内保存啦需要指定的this * @param {*} context * @param {...any} arg * @returns */Function.prototype.myBind = function (context, ...arg) { // 判断参数 arg = arg ? arg : []; // 如果使用new的话 constructor会指向newFun // 应该指向调用bind()的函数 // 以temp做为跳板, 毕竟现在this只是执行上下文 const temp = function () {}; // 由于bind 要返回一个函数, 先将this保存一下 const fn = this; // 返回一个函数, 看之后要做什么 const newFun = function (...newArg) { // 是不是要new 如果是使用new 那吗this 指向new出来的对象 if (this instanceof temp) { return fn.apply(this, [...arg, ...newArg]); } // 没有使用new的情况 this 使用传递进来的this return fn.apply(context, [...arg, ...newArg]); }; // 继承 防止new之后创建此对象的函数的引用为const newFun = function(){} temp.prototype = fn.prototype; // constructor 属性返回对创建此对象的函数的引用 newFun.prototype = new temp(); return newFun;};function show() { console.log(this);}var duyio = { x: 20,};var newSbow = show.newBind(duyio, 1, 2, 3);newSbow(5); //第二次参数 会将第一次的参数插入第二次参数的前面console.log(new newSbow().constructor); // 此处的函数引用是 show()//constructor 属性返回对创建此对象的 Boolean 函数的引用