手写实现apply,call,bind
一些小练习,加深对this的动态绑定、闭包的掌握。都是些小demo,没有对传入的参数做很深的检测!
废话不说了,直接上代码
appy
1 var name = '李世海'; 2 var obj = { 3 name:'李虎峰' 4 } 5 6 Function.prototype.shApply = function (thisObj,argArray){ 7 var fn = this; 8 var thisObj = (thisObj != null &&thisObj != undefined) && typeof thisObj == 'object'?thisObj:window; 9 thisObj.fn = fn; 10 return thisObj.fn(...argArray) 11 } 12 13 function printInfo(age,gender){ 14 console.log(this.name,age,gender); 15 } 16 17 //直接调用 18 printInfo(22,'男'); 19 //使用aplly调用 20 printInfo.shApply(obj,[22,'男']); 21 22 // Function.prototype.apply()
call
1 var name = '李世海'; 2 var obj = { 3 name:'李虎峰' 4 } 5 6 Function.prototype.shCall = function (thisObj,...argArray){ 7 var fn = this; 8 var thisObj = (thisObj != null &&thisObj != undefined) && typeof thisObj == 'object'?thisObj:window; 9 thisObj.fn = fn; 10 return thisObj.fn(...argArray) 11 } 12 13 function printInfo(age,gender){ 14 console.log(this.name,age,gender); 15 } 16 17 //直接调用 18 printInfo(22,'男'); 19 //使用aplly调用 20 printInfo.shCall(obj,22,'男'); 21 22 23 // Function.prototype.call()
bind
1 var name = '李世海'; 2 var obj = { 3 name:'李虎峰' 4 } 5 6 Function.prototype.shBind = function (thisObj,...argArray){ 7 var fn = this; 8 var thisObj = (thisObj != null &&thisObj != undefined) && typeof thisObj == 'object'?thisObj:window; 9 thisObj.fn = fn; 10 return function(...args){ 11 return thisObj.fn(...argArray,...args); 12 } 13 } 14 15 function printInfo(age,gender){ 16 console.log(this.name,age,gender); 17 } 18 19 //直接调用 20 printInfo(22,'男'); 21 //使用bind改变函数中this的指向 22 var newPrintInfo = printInfo.shBind(obj,22,'男'); 23 newPrintInfo(); 24 // 分开传参 25 var newPrintInfo = printInfo.shBind(obj,22); 26 newPrintInfo('男'); 27 28 Function.prototype.bind()
保持好奇,保持学习,做时间的朋友