Constructor, operator "new"
construction function 主要用來建構可以重複使用的物件。
Constructor function
constructor function 是一般的函式,不過有 2 個規定:命名第一個字母要大寫,要用 new 運算符號。
function User(name) {
this.name = name;
this.isAdmin = false;
}
let user = new User("Jack");
alert(user.name); // Jack
alert(user.isAdmin); // false
// 過程
function User(name) {
// this = {}; (implicitly)
// add properties to this
this.name = name;
this.isAdmin = false;
// return this; (implicitly)
}
// 結果
let user = {
name: "Jack",
isAdmin: false
};
// 有很複雜的物件可以使用只能用一次的 constructor function
let user = new function() {
this.name = "John";
this.isAdmin = false;
// ...other code for user creation
// maybe complex logic and statements
// local variables etc
};Constructor mode test: new.target
Return from constructors
通常 constructor function 沒有 return,主要的功用是傳值進物件,但有 return 的劃分為 2 種情形。
返回物件取代掉 this
返回原始值被忽略
Methods in constructor
constructor function 也可以創造方法。
Last updated
Was this helpful?