' P '

whatever I will forget

JavaScript ES6 メモ

以前使ってた時はES5だったので随時追加式メモ

スコープ

当たり前ではあるが一応

var myVar = 1;
function myFunc() {
  var myVar = 2;
  console.log(myVar); // 2
}
myFunc();
console.log(myVar) // 1

function内は2になって最後のconsole.logは1になります。

var myVar = 1;
if (true) {
  var myVar = 2;
  console.log(myVar); // 2
}
console.log(myVar)  // 2

varで変数を定義すると、ブロックスコープ {}をサポートしていないため、どちらも2と表示される。

これを letで定義すると...

let myVar = 1;
if (true) {
  let myVar = 2;
  console.log(myVar);  // 2
}
console.log(myVar) // 1

となる。
letブロックスコープをサポートしたというわけです。

オブジェクトの定義

前半部分がこれまで。ES6はいきなりプロパティ変数をオブジェクトに入れられる。

let firstName = "test", lastName = "taro";
let user = {
  fst : firstName,
  lst : lastName
}
console.log(user);
let user2 = {firstName, lastName};
console.log(user2);
(2) {fst: "test", lst: "taro"}
fst : "test"
lst : "taro"
(2) {firstName: "test", lastName: "taro"...}
firstName : "test"
lastName : "taro"

ArrayやObjectのアクセス

Array

let numbers = [1, 2, 3, 4]; 

let [one, two, three, four] = numbers;
console.log(one); // 1

Object

const APPLE = {
  type : "red delicaious",
  color : "red",
  size: "large"
}

const {type, color} = APPLE;
console.log(color); // red

fat arrowの使用

let result = function (i,j) {
  return i+j; 
}
console.log(result(2,3));

上記が下記で表現できるように

let result = (i,j) => i+j; 
console.log(result(2,3));  

thisself

これまでは下記コードをするとundfinedが表示されていた

let message = {
  hello : 'Hello',
  names : ['Sue', 'Joe'],
  showMessage: function() {
    this.names.forEach(function(name) {
      console.log(this.hello + ' ' + name);
    });
  }
}
message.showMessage();  

selfを使用することによってグローバルスコープではなく、showMessage()内のスコープを取得できる

let message = {
  hello : 'Hello',
  names : ['Sue', 'Joe'],
  showMessage: function() {
    let self = this;
    this.names.forEach(function(name) {
      console.log(self.hello + ' ' + name);
    });
  }
}
message.showMessage();  

function(name)と記載せずにname => { console.log(this.hello + ' ' + name);とも記載が可能