标签:
其实项目中还没有用到。
但自己还是想逐步了解一些高级的JS语法,不是为了炫技,也不像找前端的工作。
主要目的是:1.学习设计思想,提升解决问题的能力2.让自己的脑子动起来,别太笨。
简单的几句话总结一下call,apply和bind:
bind function.bind(thisArg[,arg1[,arg2[,argN]]])
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script language="JavaScript"> var checkNumeericRange = function(value){ if(typeof value !==‘number‘) return false; else return value>=this.minimum && value<=this.maxmum; } var checkNumeericRange1 = function(value,r){ if(typeof value !==‘number‘) return false; else return value>=r.minimum && value<=r.maxmum; } var range = {minimum:10,maxmum:20}; var boundCheckNumericRange = checkNumeericRange.bind(range); var result = boundCheckNumericRange(12); var result1=checkNumeericRange(12); var result2=boundCheckNumericRange(21); var result3=boundCheckNumericRange(‘adssad‘); var result4=checkNumeericRange1(12,range); document.writeln(result);//true document.writeln(result1);//false document.writeln(result2);//false document.writeln(result3);//false document.writeln(result4);//true </script> </body> </html>
第二个:bind改变原有的this对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script language="JavaScript"> var originalObject={ minimum:50, maxmum:100, checkNumericRange:function(value){ if(typeof value !== ‘number‘) return false; else return value>=this.minimum && value<=this.maxmum; } } var result=originalObject.checkNumericRange(10); document.writeln(result); var range={minimum:10,maxmum:20}; //MSDN的原版写法 // Create a new version of the checkNumericRange function that uses range. var boundObjectWithRange = originalObject.checkNumericRange.bind(range); // Check whether 10 is in the numeric range. var result = boundObjectWithRange(10); // 这样写也可以: // var boundObjectWithRange=originalObject.checkNumericRange.bind(range,39); // var result=boundObjectWithRange() document.write(result); </script> </body> </html>
第三个:利用[,arg1[,arg2[,argN]]]传入参数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script language="JavaScript"> var displayArgs = function(val1,val2,val3,val4){ document.write(val1 + " " + val2 + " " + val3 + " " + val4); } var emptyObject = {}; var displayArgs2 = displayArgs.bind(emptyObject,12,"a"); displayArgs2("b","c"); </script> </body> </html>
标签:
原文地址:http://www.cnblogs.com/yueyanglou/p/4599469.html