🔸prototype

function's `prototype` property.

JSvalueobjectfunction ⟩ prototype

only a relatively small number of objects have a "prototype" property, it's these objects that define the prototypes for all the other objects.

let obj = new F();    // obj.__proto__ === F.prototype

⚖️ function's prototype vs. class's prototype (property)

  • function's prototype is writable. (can be reassigned)

  • class's prototype is read-only(can't be reassigned)

function's prototype (property)

  • is (only) used as a new object's prototype.

  • should be either an object or null, other values won’t work

👉 javascript.info

⭐️ every function has a default prototype. (with the only constructor property that points back to the function itself)

function A(){}
A.prototype.constructor === A        // true

if A.prototype is an object, then let a = new A() will set a.__proto__ = A.prototype.

⭐️ 注意:

如果改寫函數的 prototype,如:A.prototype = {},則往後的 new A() 物件就再也沒有 constructor 屬性,除非你自己在新的 prototype 中再加入 constructor 屬性❗️(舊的物件沒有影響,因為舊的 prototype 依然存在,舊的物件的 [[Prototype]] 屬性沒有改變,依然指向舊的 prototype)

Last updated