美文网首页
箭头函数与function的区别

箭头函数与function的区别

作者: townYouth | 来源:发表于2021-06-08 11:06 被阅读0次

1.写法不同

function fn(a, b){
    return a + b;
}
//arrow function
var foo = (a, b)=>{ return a + b };

2.使用function定义的函数,this的指向随着调用环境的变化而变化的,而箭头函数中的this指向是固定不变的,一直指向的是定义函数的环境。

//使用function定义的函数
function foo(){
    console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window

3.function是可以定义构造函数的,而箭头函数不可以。

//使用function方法定义构造函数
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}

//尝试使用箭头函数
var Person = (name, age) =>{
    this.name = name;
    this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

4.由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let const定义的时候更不必说)关键词,而var所定义的变量不能得到变量提升,故箭头函数一定要定义于调用之前

foo(); //123
function foo(){
    console.log('123');
}

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
    console.log('456');
};

转载自:https://blog.csdn.net/github_38851471/article/details/79446722

相关文章

网友评论

      本文标题:箭头函数与function的区别

      本文链接:https://www.haomeiwen.com/subject/qcbdeltx.html