面試時遇到下面一段代碼:面試
function A () {} function B () {} A.prototype = { fun: function () {} } var a =new A () console.log(a.constructor === A) console.log(A.prototype.constructor === A) console.log(a.hasOwnProperty('constructor'))
你們猜到上面的結果是啥了嗎?正確答案是 false false false函數
咱們建立的每一個函數都有一個prototype(原型)對象,這個屬性是一個指針,指向一個對象。在默認狀況下,全部原型對象都會自動得到一個constructor(構造函數)屬性,這個屬性是一個指向prototype屬性所在函數的指針。當調用構造函數建立一個新實例後,該實例的內部將包含一個指針(繼承自構造函數的prototype),指向構造函數的原型對象。prototype
但有一點咱們是要注意的,當咱們將構造函數的prototype設置爲等於一個以對象字面量形式建立的新對象時,constructor屬性再也不指向該構造函數。指針
該題目就是有了 對A的prototype的從新設置,致使A.prototype 不在指向A的構造函數。因此上面前兩個都返回false。而constructor 是繼承自prototype ,因此hasOwnProperty('constructor') 是false.
若是A.prototype從新賦值後但願constructor仍指向A的話,咱們能夠在字面對象里加一個constructor屬性讓它指向A。code
A.prototype = { fun: function () {}, constructor: A }
這樣就能夠返回true了對象
A.prototype = new B() var b = new A() console.log(b.constructor === A) console.log(B.prototype.constructor === A) console.log(b.constructor.prototype.constructor === A) console.log(b.hasOwnProperty('constructor'))
上面的都是返回false, 你答對了嗎?繼承