0
1

More than 3 years have passed since last update.

JavaScript初心者が引っかかったthisのスコープ、1+"1"、==と===の違い、undefinedの判定についてまとめる

Last updated at Posted at 2020-08-25

柔軟性が高いjavascript。
型宣言とか厳しめの言語を書いていると、javasciptの意外のところに引っ掛かりして、、、。

1+"1"ってどうなるの?

1+1; //2という値が返る
1+"1"; //文字列として連結され、"11"という文字列が返る
"1"+1; //文字列として連結され、"11"という文字列が返る
"1"+"1"; //文字列として連結され、"11"という文字列が返る

文字列を数値変換しなかったら、ある分岐を通らなかった、、

var a = "1"
if ( 1 === a ){
  console.log("実行されてない")
}

if ( 1 == a ){
 console.log("実行される")
}

1 === "1" はfalse、 1 == "1" のtrueの理由

==は、右辺と左辺の値を同じ型に変換する!
つまり、 === は型までみて同じかどうかを判断している

1 == 1; //true
1 == "1"; //true
1 == true //true
"1" == true; //true
"true" == true; //false
1 === 1; //true
1 === "1"; //false
1 === true; //false
"1" === true; //false

undefined, null、空文字のtrue, falseどっち?

var params;
if (params) {
  console.log("初期化されていないため、実行されない");
}
params = null;
if (params) {
  console.log("nullはfalseとみなされるため、実行されない");
}
if (0) {
  console.log("空文字はfalseとみなされるため、実行されない");
}
if ("") {
  console.log("空文字はfalseとみなされるため、実行されない");
}
params = "set";
if (params) {
  console.log("paramsに文字列が設定されています");
}
console.log("aaa" && "bbb"); //bbb
console.log("aaa" || "bbb"); //aaa
console.log(0 || "ccc"); //cccc

thisのスコープってどこまでだっけ?

thisとは?

その時のオブジェクトを指す

function hello() { console.log('my name is' + this.name )};

var person1 = { name: 1, hello: hello };
var parson2 = { name: 2, hello: hello };

person1.hello(); // my name is 1
person2.hello(); // my name is 2

あれ、countが増えない...?

書いたコード

function Timer1() {
  this.count = 0;
  setInterval(function() {
    this.count ++;
   }, 1000);
}
var timer1 = new Timer1()l

setInterval(() => console.log(timer1), 10000);

実行した結果

Timer1 {count: 0}
Timer1 {count: 0}
Timer1 {count: 0}

=> thisはグローバルオブジェクトなので、countを参照できない!

countを参照できるようにするには?

解決方法1

コード

function Timer2() {
  _this = this;
  _this.count = 0;
  setInterval(function() {
    _this.count ++;
   }, 1000);
}
var timer2 = new Timer2()l

setInterval(() => console.log(timer2), 10000);

実行結果

Timer2 {count: 1}
Timer2 {count: 2}
Timer2 {count: 3}

=> スコープ内変数に代入することで、countを参照できるようになる!

解決方法2

コード

function Timer3() {
  this.count = 0;
  setInterval(function() {
    this.count ++;
   }.bind(this), 1000);
}
var timer3 = new Timer3();

setInterval(() => console.log(timer3), 1000);

実行結果

Timer3 {count: 1}
Timer3 {count: 2}
Timer3 {count: 3}

=> bind関数で、thisを追加して呼び出すことで、countを参照できる!

解決方法3

function Timer4() {
  this.count = 0;
  setInterval{() => {
    this.count++;
  }, 1000)
}
var timer4 = new Timer4();
setInterval(() => console.log(timer4), 1000);

実行結果

Timer4 {count: 1}
Timer4 {count: 2}
Timer4 {count: 3}

=> アロー関数にして、thisを束縛しないようにする!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1