实现一个bind方法

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 = 'https://www.it610.com/article/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);

    推荐阅读