js function test if it is called by new operator

在javascript function中,如果要強制使用new,可以參考以下nodejs cluster/worker.js的範例

他這邊利用檢查this是否是instanceof Worker,在一般情況下

但是在new operator下


The new keyword does the following things:
1. Creates a blank, plain JavaScript object;
2. Links (sets the constructor of) this object to another object;
3. Passes the newly created object from Step 1 as the this context;
4. Returns this if the function doesn’t return its own object.

This entry was posted in nodejs. Bookmark the permalink.

Leave a Reply