constructor function 是一般的函式,不過有 2 個規定:命名第一個字母要大寫,要用 new 運算符號。
functionUser(name) {this.name = name;this.isAdmin =false;}let user =newUser("Jack");alert(user.name); // Jackalert(user.isAdmin); // false// 過程functionUser(name) {// this = {}; (implicitly)// add properties to thisthis.name = name;this.isAdmin =false;// return this; (implicitly)}// 結果let user = { name:"Jack", isAdmin:false};// 有很複雜的物件可以使用只能用一次的 constructor functionlet user =newfunction() {this.name ="John";this.isAdmin =false;// ...other code for user creation// maybe complex logic and statements// local variables etc};
Constructor mode test: new.target
// 可以用 new.target 檢測是否用 new 來創造物件。functionUser() {alert(new.target);}// without "new":User(); // undefined// with "new":newUser(); // function User { ... }// 通常使用在函式庫內,確保用 new 創造物件。functionUser(name) {if (!new.target) { // if you run me without newreturnnewUser(name); // ...I will add new for you }this.name = name;}let john =User("John"); // redirects call to new Useralert(john.name); // John
Return from constructors
通常 constructor function 沒有 return,主要的功用是傳值進物件,但有 return 的劃分為 2 種情形。
返回物件取代掉 this
返回原始值被忽略
// 返回物件functionBigUser() {this.name ="John";return { name:"Godzilla" }; // <-- returns an object}alert( newBigUser().name ); // Godzilla, got that object ^^// 返回原始值functionSmallUser() {this.name ="John";return; // finishes the execution, returns this// ...}alert( newSmallUser().name ); // John// 若無參數,可以忽略括號,但不是好的寫法let user =new User; // <-- no parentheses// same aslet user =newUser();
Methods in constructor
constructor function 也可以創造方法。
functionUser(name) {this.name = name;this.sayHi=function() {alert( "My name is: "+this.name ); };}let john =newUser("John");john.sayHi(); // My name is: John/*john = { name: "John", sayHi: function() { ... }}*/