1.constructor關鍵字
- constructor關鍵字用于在類定義塊內部創建類的建構式,
- 方法名constructor會告訴解釋器在使用new運算子創建類的新實體時,應該呼叫這個函式,
- 建構式的定義不是必需的,不定義建構式詳單與將建構式定義為空函式,
2.實體化
- 使用new運算子實體化Person的操作等于使用new呼叫其建構式,
- JavaScript解釋器知道使用new和類意味著應該使用constructor函式進行實體化,
- 使用new呼叫類的建構式會執行如下操作,
(1)在記憶體中創建一個新物件,
(2)這個新物件內部的[[Prototype]]指標被賦值為建構式的prototype屬性,
(3)建構式內部的this被賦值為這個新物件,
(4)執行建構式內部的代碼,
(5)如果建構式回傳非空物件,則回傳該物件;否則,回傳剛創建的新物件,
class Person{
constructor(name){
console.log(arguments.length);
this.name = name || null;
}
}
let p1 = new Person;//0
console.log(p1.name);//null
let p2 = new Person();//0
console.log(p2.name);//null
let p3 = new Person('Jake');//1
console.log(p3.name);//Jake
- 類實體化時傳入的引數會用作建構式的引數,如果不需要引數,則類名后面的括號也是可選的,
class Person{
constructor(override){
this.foo = 'foo';
if(override){
return{
bar:'bar'
}
}
}
}
let p1 = new Person(),
p2 = new Person(true);
console.log(p1);//Person {foo: "foo"}
console.log(p1 instanceof Person);//true
console.log(p2);//{bar: "bar"}
console.log(p2 instanceof Person);//false
- 如果回傳的不是this物件,而是其他物件,那么這個物件不會通過instanceof運算子檢測出跟類有關聯,
function Person(){};
class Animal{}
let p = Person();//將window作為內部物件
let a = Animal();//TypeError: Class constructor Animal cannot be invoked without 'new'
- 普通建構式如果不使用new呼叫,那么就會以全域的this(通常是window)作為內部物件,
- 呼叫類建構式時如果忘了使用new則會拋出錯誤,
2.把類當成特殊函式
class Person{}
console.log(Person);//class Person{}
console.log(typeof Person);//function
- 從各方面來看,ECMAScript類就是一種特殊函式,
class Person{}
console.log(Person.prototype);//{constructor:f()}
console.log(Person === Person.prototype.constructor);//true
let p = new Person();
console.log(p instanceof Person);//true
- 類識別符號有prototype屬性,而這個原型也有一個constructor屬性指向類自身,.
- 可以使用類識別符號來檢查建構式原型是否存在于實體的原型鏈中,
class Person{};
let p1 = new Person();
console.log(p1.constructor === Person);//true
console.log(p1 instanceof Person);//true
console.log(p1 instanceof Person.constructor);//false
let p2 = new Person.constructor();
console.log(p2.constructor === Person);//false
console.log(p2 instanceof Person);//false
console.log(p2 instanceof Person.constructor);//true
- 在類的背景關系中,類本身在使用new呼叫時就會被當成建構式,重點在于,類中定義的constructor方法不會被當成建構式,在對它使用instanceof運算子時會回傳false,如果在創建實體時直接將建構式當成普通函式來使用,那么instanceof運算子的回傳值會反轉,
let classList = [
class{
constructor(id){
this.id_ = id;
console.log(`instance ${this.id_}`)
}
}
];
function createInstance(classDefinition,id){
return new classDefinition(id);
}
let foo = createInstance(classList[0],3141);//instance 3141
- 可以像其他物件或函式參考一樣把類作為引數傳遞,
let p = new class Foo{
constructor(x){
console.log(x);
}
}('bar');//bar
console.log(p)//Foo{}
- 與立即呼叫函式運算式相似,類也可以立即實體化,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/289315.html
標籤:其他
上一篇:JavaScript面向物件思想
