Constructor, operator "new"
construction function 主要用來建構可以重複使用的物件。
Constructor function
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
Methods in constructor
Last updated