本身對JS中constructor的誤解

在JS中,構造器(constructor)是用來用new關鍵詞來建立對象的一個普普統統的函數,爲了在形式上區別通常的函數,第一個字母一般大寫。函數

function Person(){};  // constructor
var wenzhe = new Person();

這就是基本的格式,咱們能經過wenzhe.constructor或者Person.prototype.constructor來查看咱們的構造函數,可是查看的這個構造函數只是表象。它不參與對象的構造,也就是說這個屬性只是存儲了構造函數的映像而已,沒啥用。真正構造對象的那個構造函數永遠是new後面那個。即它只是爲了方便人查看構造函數而存在的this

function Number() {
    this.name = 'Number';
 }

 function Two() {}

 function Three() {
    this.name = 'Three'
 }

Two.prototype = new Number(); 
Two.prototype.constructor === Number.prototype.constructor; // true
Two.prototype.constructor = Three;
var a = new Two();
a.name // shape;
a.constructor // ..three...

因此說,當咱們 Two.prototype = new Number()以後,最好再添加 Two.prototype.constructor = Two,這樣避免混淆。prototype

咱們能夠用 console.log(wenzhe instanceof Person) 判斷對象和構造函數是否對應
,雖然上面那個a.constructor是指向Three,可是console.log(a instanceof Three) 依然爲false。code

還有一點就是 object literal 或者 Object constructor建立的對象的constructor指向Object對象

相關文章
相關標籤/搜索