ES 6の関数
13436 ワード
既存のブログの内容をDevelopgに移行した記事です.
1.ES 6の関数を区別する
分割コンストラクション関数prototypeハイパードキュメントの一般的な関数OOXOメソッド(ショートカット)XXOO矢印関数XXXX
2.方法
ES 6では,ショートカットで作成した関数のみがメソッドと考えられる.
方法は[HomeObject]を有し,
super
を用いることができる.3.矢印関数
3.1. 制定法
// ()는 매개변수가 들어갈 자리, 한 줄일 경우 return 생략 가능
const arrow1 = () => console.log("화살표 함수");
// 매개변수가 있을 시 () 생략 가능
const arrow2 = (x) => x * x;
// 매개변수가 두 개 이상일 경우 () 생략 불가
const arrow3 = (x, y) => x * y;
// 코드가 두 줄 이상인 경우 {} 생략 불가
const arrow4 = (x, y) => {
console.log(x);
console.log(y);
};
3.2. 長所
non-constructorなので、プロトタイプは作成しません.
パラメータ名を繰り返し宣言することはできません.
矢印関数のthis、arguments、super、new.targetは矢印関数ではなく位相走査を参照するので,重畳関数として便利に用いることができる.
3.3. 矢印関数のthis
矢印関数のthis、arguments、super、new.targetは親スキャン(矢印関数ではなく)を参照します.
// 즉시 실행 함수의 this는 전역 객체를 가리킨다.
// call을 사용하여 호출가 동시에 새 객체를 this에 바인딩한다.
// 화살표함수는 자체적 this 바인딩이 없어 상위 스코프의 this를 찾는다
// 따라서 새 객체가 화살표 함수의 this가 된다.
(function () {
const foo = () => console.log(this);
foo();
}.call({ a: 1 })); // { a: 1 }
矢印関数のthisはcall、apply、bindに変更できません.
window.name = "Yu";
const arrow = () => console.log(this.name);
arrow.call({ name: "Kim" }); // Yu
したがって、this
を使用する메소드
または프로토타입 메소드
を矢印関数として定義することは危険である.3.4. 矢印関数のsuper、arguments
superをバインドするのではなく、親scopeのsuperを取得します.
class Base {
constructor(name) {
this.name = name;
}
sayHi() {
return `Hi! ${this.name}`;
}
}
class Derived extends Base {
// super 키워드는 ES6 메소드 내에서만 사용 가능하다.
// 화살표 함수는 함수 자체의 super 바인딩이 없다.
// 화살표 함수 sayHi의 상위 컨텍스트는 constructor이다.
// 화살표 함수 sayHi의 super는 constructor의 super를 가리킨다.
// 클래스 필드 정의 제안으로 클래스 필드에 화살표 함수를 할당한다.
sayHi = () => `${super.sayHi()} how are you doing?`;
}
// Derived의 constructor는 Derived.prototype에 존재한다.
// 따라서 constructor의 super는 Base.prototype이 된다.
console.log(Object.getOwnPropertyNames(Derived.prototype)); // [ 'constructor' ]
4.Restパラメータ
...arg
のように前にあります...一緒に書きます.パラメータとして使用する場合の関数です.長さに影響しません.
restパラメータは1つしか使用できません.
function sum(...args) {
// Rest 파라미터 args에는 배열 [1, 2, 3, 4, 5]이 할당된다.
return args.reduce((pre, cur) => pre + cur);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
5.パラメータデフォルト
function logName(name = "Lee") {
console.log(name);
}
logName(); // Lee
logName(undefined); // Lee
logName(null); // null
パラメータに値が渡されなかったり、定義されていない場合に入力するデフォルト値を設定できます.
restパラメータはデフォルト値を設定できません.
Reference
この問題について(ES 6の関数), 我々は、より多くの情報をここで見つけました https://velog.io/@seongkyun/ES6의-함수テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol