JS對象中,在原型鏈上找到屬性後 最終將值拷貝給原對象 而不是引用

遇到一個面試題面試

要求寫一個函數A,每次進行new操做時候能輸出2,3,4,5...函數

new A() // 輸出2this

new A() // 輸出3prototype

new A() // 輸出4對象

 

 

 

function A()原型

{io

  this.a++console

  console.log(this.a)function

}引用

A.prototype.a = 1

 

這樣寫是錯誤的,由於實例化對象中的a屬性並非原型上的引用,而是把原型上的a給拷貝了一份給a。

因此這樣每次輸出都是2.

 

 

正確答案:

function A()

{

  this.__proto__.a++

  console.log(this.a)

}

 

A.prototype.a = 1

 

// 2,3,4,5..

 

 

或者其實我掛載到函數上成爲靜態屬性也能夠

 

function A(){

  console.log(this.__proto__.constructor.a++)

}

A.a = 1

 

..

相關文章
相關標籤/搜索