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 运算符
// 判断Fb 是否是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);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。