Function.prototype.myBind = function () { // 保留this 此时this指向 greeting let that = this // this必须是一个函数 bind 肯定绑定一个函数 if (typeof that !== 'function') { throw new TypeError( 'Function.prototype.bind - ' + 'what is trying to be bound is not callable' ) } // arguments 是mybind传入的所有参数 let thatArg = arguments[0] // 咱们要把bind中残余的参数,全副传入到返回的函数中 // 第一个参数曾经用了,所以要从下标1开始取值 args为bind外面的参数除了第一个之后的参数 let args = Array.prototype.slice.call(arguments,1) let Fb = function () { // 返回的函数中可能有参数,要把bind外面的参数和返回办法外面的参数合并 // args 是bind的参数 // Array.prototype.slice.call(arguments,1) 是以后返回函数的参数 let _args = [...args,Array.prototype.slice.call(arguments)] // bind会创立一个新的绑定函数,也能够用new 运算符 // 判断Bfn 是否是new 函数 进去的 if(this instanceof Fb){ return that.apply(this,_args) }else{ return that.apply(that,_args) } } let fnop = function(){} if(that.prototype){ fnop.prototype = that.prototype } Fb.prototype = new fnop() return Fb}var obj = { name: 'Smiley' }var greeting = function (str, lang) { this.value = 'greetingValue' console.log('Welcome ' + this.name + ' to ' + str + ' in ' + lang)}var objGreeting = greeting.myBind(obj, 'the world')// objGreeting('JS');var newObj = new objGreeting('JS');console.log(newObj.value);