LoginSignup
14
20

More than 5 years have passed since last update.

JSオブジェクトにおけるnew演算子の役割をちゃんと理解する

Last updated at Posted at 2018-01-14

なんとなくでJavaScript書いてると見落としがちなnew演算子の役割についてメモがてら書いておきます。

まずどういう時にnewを使うかというと

var obj1 = new Object();
var obj2 = {};

console.log(obj1); // Object {}
console.log(obj2); // Object {}

どちらでもオブジェクトは生成できます。

しかし、newを使った時とそうでない時の違いは明白。

var myFunc = function(){
    this.prop1 = 'bar';
    this.prop2 = 'foo';
    this.method = function(){
        return this.prop1 + this.prop2;
    }
}

var obj1 = new myFunc();
var obj2 = myFunc();

console.log(obj1.method()); // barfoo
console.log(obj2.method()); // エラーになる

もう一つ例を挙げると、

var myFunc = function(){
    this.prop1 = 'bar';
}

var obj1 = new myFunc();
var obj2 = myFunc();

console.log(obj1); // myFunc {prop1: "bar"}
console.log(obj2); // undefind

obj2はundefindになっています。

通常、JavaScriptの関数は、return文が明示的に指定されていない場合、自動的に呼び出し元にはundefindが返却されます。
newを用いて呼び出された場合は、return文が書かれていようがいまいが、自動的にオブジェクトのインスタンスが返却されます。

最後にわかりやすい極端な例を挙げます。

var myFunc = function(){
    this.prop1 = 'bar';
    return 'foo';
}

var obj1 = new myFunc();
var obj2 = myFunc();

console.log(obj1); // myFunc {prop1: "bar"}
console.log(obj2); // foo

newを用いない場合はただの関数呼び出しになっています。

14
20
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
14
20