call的实现原理
//context就是要重新指向的对象,根据下面调用方法的情况看,就是a
Function.prototype.mycall = function(context){
var context = context || window //不传参数,默认指向window
context.fn = this
//往传入的对象a身上添加一个属性,它的值是函数mycall的调用者,根据下面调用方法的情况看,这里是函数func
//也就是说a变成了这样
// var a = {
// name:'法外狂徒张三',
// func:function(x,y){
// console.lgo(this.name) //这样this就成功指向了a
// console.log(x+y)
// }
// }
//arguments是js内置对象,它只是一个类数组对象,存放实参
//console.log(arguments),值为{ 0: '1', 1: '2'}
let arg = [...arguments].slice(1) //截取context后面的参数
let result = context.fn(...arg) //执行刚刚添加的方法func
// 删除 fn
delete context.fn
return result
}
function func(x,y){
//this成功指向了a后,就可以拿到name的值了
return this.name + '被判处年限' + (x + y) + '年' //法外狂徒张三被判处年限3年
}
const a = {
name:'法外狂徒张三'
}
func.mycall(a,1,2)
apply的实现原理
apply和call区别在于apply第二个参数是数组,而call是以逗号为分割一个个传入
Function.prototype.myapply = function(context){
var context = context || window
context.fn = this
var result
// 需要判断是否存在第二个参数
// 如果存在,就将第二个参数展开
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
function func(x,y){
return this.name + '被判处年限' + (x + y) + '年' //法外狂徒张三被判处年限3年
}
const a = {
name:'法外狂徒张三'
}
func.myapply(a,[1,2])
bind的实现原理
bind 和其他两个方法作用也是一致的,但是该方法会返回一个函数。
Function.prototype.mybind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
var that = this
var args = [...arguments].slice(1)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
return new that(...args, ...arguments)
}
return that.apply(context, args.concat(...arguments))
}
}
function func(x,y){
return this.name + '被判处年限' + (x + y) + '年' //法外狂徒张三被判处年限3年
}
const a = {
name:'法外狂徒张三'
}
let b = func.mybind(a,1,2)
b()