在javascript function中,如果要強制使用new,可以參考以下nodejs cluster/worker.js的範例
他這邊利用檢查this是否是instanceof Worker,在一般情況下
- https://www.w3schools.com/js/js_this.asp
- In a function,
this
refers to the global object. - In a function, in strict mode,
this
isundefined
.
- In a function,
但是在new operator下
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
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 thethis
context;
4. Returnsthis
if the function doesn’t return its own object.