JavaScript 中的常规函数与箭头函数?
front end technologyjavascriptobject oriented programming
常规函数与箭头函数
箭头函数用于简洁地编写代码。常规和箭头函数的工作方式相似,但它们之间存在一些差异。让我们简要讨论一下这些差异。
箭头函数的语法
let x = (params) => { // code };
常规函数的语法
let x = function functionname(params){ // code };
"this"的用法关键字
在箭头函数中无法使用"this"关键字,而在常规函数中可以使用而不会受到任何干扰。
示例
在下面的例子中,在对象"num"内使用了regular(rectangle)和arrow(square)函数,该对象由len(length)和bre(breadth)属性组成。我们的目标是使用箭头函数找到正方形的面积(len*len),使用常规函数找到矩形的面积(len*bre)。但由于"this"关键字在箭头函数中不起作用,正方形的面积值将返回为"NaN",而使用常规函数,我们得到了矩形的精确面积,如输出中所示。
<html> <body> <script> var num = { len: 12, bre: 13, square:() => { document.write(this.len * this.len); }, rectangle(){ document.write(this.len * this.bre); } }; num.square(); document.write("</br>"); num.rectangle(); </script> </body> </html>
输出
NaN 156
"new"关键字的使用
箭头函数不是"可构造"而是"可调用",因此关键字"new"在这里不起作用,而常规函数既是"可调用"又是"可构造",因此"new"关键字在这里起作用。
示例
在下面的示例中,使用"new"关键字,一些参数已传递给常规函数和箭头函数。但是由于箭头函数不是&;可构造&;,我们将收到错误,而常规函数则会获得合法的输出。
<html> <body> <script> var word = function(){ document.write(JSON.stringify(arguments)); /// 执行'{"0":"Tutorix","1":"Tutorialspoint"}'作为输出 }; new word("Tutorix","Tutorialspoint"); var newword = ()=> { document.write(JSON.stringify(arguments)); //执行 'newword is not a construction' 作为输出 }; new newword("Tutorix","Tutorialspoint"); </script> </body> </html>