手撸JS call,apply,bind
call的实现
Function.prototype.Call=function(...args){ var context=args[0]||window; var argArr=args.slice(1) context.fn=this; //相当于给context加了一个fn属性,属性值为当前函数,在对象里面定义函数相当于把函数的this改为context对象了 var result=context.fn(...argArr) delete context.fn return result; } var obj = { name: "hty", sex: "男" } function fn(age, pro) { console.log(`${this.name}是${this.sex}`)//hty是男 console.log(`今年${age}职业是${pro}`)//今年24职业是前端攻城狮 } fn.Call(obj, "24", "前端攻城狮")
apply的实现
Function.prototype.Apply=function(...args){ var context=args[0]||window; var argArr=args.slice(1) context.fn=this; var result=context.fn(...argArr[0]) delete context.fn return result; } var obj = { name: "hty", sex: "男" } function fn(age, pro) { console.log(`${this.name}是${this.sex}`)//hty是男 console.log(`今年${age}职业是${pro}`)//今年24职业是前端攻城狮 } fn.Apply(obj,["24", "前端攻城狮"])
bind的实现
Function.prototype.Bind=function(...args){ var context=args[0]||window; var args=args.slice(1) var fbind=this; fBound=function(...value){ //bind要返回函数 fbind.apply(context,args.concat(value)) } return fBound } var obj = { name: "hty", sex: "男" } function fn(age, pro,type) { console.log(`${this.name}是${this.sex}`)//hty是男 console.log(`今年${age}职业是${pro}他在${type}`)//今年24职业是前端攻城狮他在努力 } fn.bind(obj,"24", "前端攻城狮")("努力")
相关推荐
lzzyok 2020-10-10
无情的你无情的雨 2020-06-16
chunianyo 2020-06-04
grantlee 2020-05-28
xjp 2020-05-26
天空一样的蔚蓝 2020-05-02
nangongyanya 2020-04-19
shufen0 2020-04-14
humanbeng 2020-03-05
Alanxz 2020-03-04
liwf 2020-02-17
歆萌 2020-02-10
tianchaoshangguo 2020-01-04
julien 2020-01-02
齐天大圣数据候 2019-12-28
杨友山 2019-12-25
GavinZhera 2019-12-19
oLeiShen 2019-12-15
chunianyo 2019-12-12