LoginSignup
5
4

More than 5 years have passed since last update.

JavaScriptのnewの知られざる2番目の使い方

Last updated at Posted at 2018-11-08

あまり良いタイトルではないですが
2つの使い方があるよ、という話です。

this についてここ(JavaScriptのthis(コンテキスト)とは?)で書いたのですが、
そういえば this の話なのに new にあまり触れてなかったなと気づいた流れで、
new といえばそういえば2通りの使い方があるなということで書いてみました。

new の2通りの使い方。

var a = new function(){ // 使い方:1つ目
  this.x = 'x1';
  this.y = 'y1';
};

var b = new function(){ // 使い方:2つ目
  var that = {};
  that.x = 'x2';
  that.y = 'y2';
  return that;
};

console.log( a.x, a.y ); // x1,y1
console.log( b.x, b.y ); // x2,y2

newで関数を実行した際にその中で、

・object(hash) を return した場合にはそれ自体が new の戻り値として返り、( ↑で書いた "2つ目")
・それ以外は [何かしら] が返ってきます。 ( ↑で書いた "1つ目")

この [何かしら] は内部的には this としてアクセスできて、外部的にはそれを代入した変数 a からアクセスできます。

a も b も外からアクセスする分には同じ動きをします。

var c = (function(){
  var that = {};
  that.x = 'x3';
  that.y = 'y3';
  return that;
}());

この c も同様の動きです。(new 使った例ではないですが)

で、「何が違うんだ?」とか「どう使い分ける?」

とかですが、b,c は全く同じなのでどちらでもいい思います。(私は c の書き方をよく使う)
結局のところ単に object(hash) を返しているだけです。
何か初期化の処理をしたいな~とかいう場合に使ってます。

※追記。関数の初期化用途の場合には new を私はよく使います。

var test = new function(){
  var _default = 'aiueo';
  return function(x){
    return x||_default;
  };
};
test(); // 'aiueo'

// "内部だけ" で使う関数を定義したい場合。
var test = new function(){
  return function(n){
    return add(n);
  };
  function add(n){
    return n+10;
  }
};
test(2); // 12

a は b,c っぽい [何かしら] が返ってきますが、[何かしら] 特有の機能が付与されているというだけの違いです。
特有の機能とは以下の暗黙のプロパティ2つに関しての話です。

[何かしら].prototype
[何かしら].constructor

b,c にもこれはあるんですけど、b,c は親の扶養家族みたいなもので、
a の new は独り立ちして一軒家を作る場合に使う、という感じです。

一軒家の話は長くなるのと、とりあえず new のこの2つについて書きたかったのでここまでで。

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