LoginSignup
4
3

More than 5 years have passed since last update.

Node.jsにおけるuse strictの挙動

Last updated at Posted at 2016-11-23

Node.jsにおけるuse strictの挙動

はじめに

use strictの振る舞いかた

  • プリミティブ型やundefinedは、use strictを用いると、ボックス化(Objectオブジェクトに変換されること)されません。そのまま、型を返すことによって速度向上につながるようです。

function foo() {
    console.log(typeof this);
}

function bar() {
    "use strict";
    console.log(typeof this);
}

 //要素ごとに型を確かめる
//this として関数に渡されたプリミティブ型はObjectとして取り扱われる
//object object object object object function object object
[123, "str", true, Symbol('abc'), [], ()=>{}, undefined, null].map(value => {return foo.call(value);} );

//use strictをthisとして関数に渡された値は、
//オブジェクトに閉じ込められることなく、そのまま関数に渡される
//number string boolean symbol object function undefined object
[123, "str", true, Symbol('abc'), [], ()=>{}, undefined, null].map(value => {return bar.call(value);} );

Note) nullの型をtypeof演算子はobjectと報告しているが、紛らわしいことに、ECMAScript標準規格によれば、これも独自の型(グローバルオブジェクトのプロパティ)である1

  • 即時関数の4種類の呼び出しの比較。
(function () {
  console.log(this); //thisはグローバルオブジェクト
})();


(function () {
  "use strict";
  console.log(this); // undefined
})();

//ここのthisは{}:module.exportsオブジェクトなので、
//console.logの引数のthisはレシーバーのオブジェクト自体,つまりmodule.exportsオブジェクトとなる。
(function () {
  console.log(this); 
}).call(this);

//上記と同じ。
(function () {
  "use strict"
  console.log(this); // this {}:module.exportsオブジェクト
}).call(this);

参考URL


  1. 一応、Effective JavaScript 項目4にも同じようなことが書いてあります。 

4
3
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
4
3