=>函数

=>es6语法中的 arrow function

(x) => x + 6

相当于

function(x){
    return x + 6;
}

与function函数区别

  1. 写法
//function
function fn(a, b){
    return a + b;
}
//arrow function
var foo = (a, b)=>{ return a + b };
  1. this的指向:

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

//使用function定义的函数
function foo(){
    console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }
//使用function定义的函数中this指向是随着调用环境的变化而变化的
//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
//使用箭头函数的时候,this的指向是没有发生变化的。
  1. 构造函数
//使用function方法定义构造函数
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}

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

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

由于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');
};

猜你喜欢

转载自blog.csdn.net/weixin_34310369/article/details/90935389
今日推荐