关于JavaScript函数、箭头函数的理解

 

ECMAScript 函数不能像传统编程那样重载。在其他语言比如Java 中,一个函数可以有两个定义,只要签名(接收参数的类型和数量)不同就行。如前所述,ECMAScript 函数没有签名,因为参数是由包含零个或多个值的数组表示的。没有函数签名,自然也就没有重载。

 

函数表达式与函数声明的区别。函数声明会在任何代码执行之前先被读取并添加到执行上下文。这个过程叫作函数声明提升(function declaration hoisting)。在执行代码时,JavaScript 引擎会先执行一遍扫描,把发现的函数声明提升到源代码树的顶部。因此即使函数定义出现在调用它们的代码之后,引擎也会把函数声明提升到顶部。

// 函数声明,没问题
console.log(sum(10, 10));
function sum(num1, num2) {
  return num1 + num2;
}
// 函数表达式,会出错
console.log(sum(10, 10));
let sum = function(num1, num2) {
  return num1 + num2;
};

关于this

使用函数表达式和函数声明定义的函数,this 指向调用的对象,即引用的是把函数当成方法调用的上下文对象。
window.color = 'red';
let o = {
  color: 'blue'
};
function sayColor() {
  console.log(this.color);
}
sayColor(); // 'red'
o.sayColor = sayColor;
o.sayColor(); // 'blue'
而箭头函数中的 this 一直引用的是定义箭头函数的上下文。因此,箭头函数不能使用 call() apply() bind() 等方法改变 this 的指向
window.color = 'red';
let o = {
  color: 'blue'
};
let sayColor = () => console.log(this.color);
sayColor(); // 'red'
o.sayColor = sayColor;
o.sayColor(); // 'red'

箭头函数没有constructor、arguments、new.target 

new function(){} // {}
new (()=>{}) // Uncaught TypeError: (intermediate value) is not a constructor

Arguments有length和callee方法,length可以用在一些不定参数的场景

const a = function(){console.log(arguments)} // Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
const bb = ()=>{console.log(arguments)} // Uncaught ReferenceError: arguments is not defined

callee可以用于递归方法中

function factorial(num){ 
 if (num <=1) { 
 return 1; 
 } else { 
 return num * arguments.callee(num-1) 
 } 
}

 

posted @ 2022-03-04 23:48  sssssssssssssrain  阅读(38)  评论(0)    收藏  举报