이 기사에서는 ES6 화살표 함수와 함수의 차이점이 무엇인지 설명합니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.
1. 쓰기가 다릅니다
// function的写法
function fn(a, b){
return a+b;
}
// 箭头函数的写法
let foo = (a, b) =>{ return a + b }
2. this의 가리키는 부분이 다릅니다
함수에서는 this가 함수를 호출하는 객체를 가리킵니다.
//使用function定义的函数
function foo(){
console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }
arrow 함수에서는 this가 항상 해당 환경을 가리킵니다. 기능이 정의되어 있습니다.
//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
setInterval(() => {
this.s1++;
console.log(this);
}, 1000); // 这里的this指向timer
// 普通函数
setInterval(function () {
console.log(this);
this.s2++; // 这里的this指向window的this
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0
//使用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
게다가 화살표 함수에는 자체 this가 없으므로 당연히 call(), apply(), 바인딩 등의 메서드를 사용할 수 없습니다. () 방향을 바꾸려면.
함수에는 호출 문 다음에 정의할 수 있는 변수 승격이 있습니다.
foo(); //123
function foo(){
console.log('123');
}
화살표 함수에는 리터럴 형식으로 값이 할당되며 변수 승격이 없습니다.
위 내용은 ES6 화살표 기능과 기능의 차이점은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!