' P '

whatever I will forget

JavaScript やはりまだ理解できていない点のまとめ

アロー変数とthisのスコープの違い

  • クラス内のメソッドからのfunction(関数)ではthisでオブジェクト内の変数は参照できない.
    • そもそもJavaScriptにおけるfunction と methodの意味を理解する.
      • functionは、functionと定義されている、いわゆる関数.
      • methodは、オブジェクトやクラスに定義されている、functionが定義されているオブジェクトプロパティ.

www.geeksforgeeks.org

  • アロー変数ならなぜか可能。なぜ?

    アロー変数は自分のthisを持たない

  • thisのスコープを遡って確認することが可能.
class test {
  constructor(param) {
    this.param = param;
  }

  testFunction() {
    const runWithArrowFunction = () => {
      console.log(`the value is ${this.param} from run with arrow function`)
    }
    function runWithFunction() {
      console.log(`the value is ${this.param} from run function`)

    }
    // ここは問題なくthisが存在する
    console.log(`the value is ${this.param} from testFunction`)

    runWithArrowFunction() // thisは123になる
    runWithFunction() // thisはなくなる
  }
}

obj = new test('123');
obj.testFunction();
the value is 123 from testFunction
the value is 123 from run with arrow function
TypeError: Cannot read properties of undefined (reading 'param')
    at runWithFunction (<anonymous>:17:40)
    at test.testFunction (<anonymous>:22:5)
    at <anonymous>:27:5
    at mn (<anonymous>:16:5455)
超参考

qiita.com

クラスメソッドからthisのアクセス

  • クラス内のfunctionからthisが使用できないのはなぜ?

クラス内のstaticメソッド

  • staticメソッドから thisで内部クラスの値にアクセスできない.
  • staticメソッドは子オブジェクトには引き継がれない.

クラスフィールド

  • そもそも何?

オブジェクトの継承とPrototype

  • 継承元のfunctionが継承されないケースはなに?
  • object.create()でprototypeチェーンは作られる.
  • Object.definePropertyを使用して継承したオブジェクトへ新しいコンストラクタプロパティを追加することができる.

コンストラクタ関数

  • コンストラクタ関数に、直接関数プロパティを追加することはできない.
function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const member = new Person("Lydia", "Hallie");
Person.getFullName = function() {
  return `${this.firstName} ${this.lastName}`;
};

// TypeError: member.getFullName is not a function
console.log(member.getFullName());
  • 下記はOK
function Car() {
    this.color = 'red';
    this.drive = function() {
        console.log("drive");
    }
}
 
const carInstance1 = new Car();
 
console.log(carInstance1); // Car {color: "red", drive: function()}
carInstance1.drive(); 

あるいは

function Car() {
    this.color = 'red';
}
Car.prototype.drive = function() {
    console.log("drive");
}
 
const carInstance1 = new Car();
  
console.log(carInstance1); // Car {color: "red"}
carInstance1.drive(); 

rara-world.com

クロージャ

  • 外側からアクセスできない擬似privateメソッドを作成する.

developer.mozilla.org