F.prototype

物件被建構函式創造時,像是 new F(),[[Prototype]] 被設置為 F.prototype。

// 建構函式有 prototype 屬性,可以繼承原型物件
let animal = {
  eats: true
};

function Rabbit(name) {
  this.name = name;
}

Rabbit.prototype = animal; // 當 new Rabbit 被創造 [[Prototype]] 的值為 animal

let rabbit = new Rabbit("White Rabbit"); //  rabbit.__proto__ == animal

alert( rabbit.eats ); // true

Default F.prototype, constructor property

// 每一個函式都有 prototype 屬性,預設為一個物件有 constructor 屬性
function Rabbit() {}

/* default prototype
Rabbit.prototype = { constructor: Rabbit };
*/

// check
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }

alert( Rabbit.prototype.constructor == Rabbit ); // true
// 什麼都不做,新的建構函式有 constructor 屬性
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }

let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}

alert(rabbit.constructor == Rabbit); // true (from prototype)
// 用 constructor 屬性創造一個跟現有構造函式一樣的物件。
// 當我們有一個物件,但不知道使用哪個構造函式,而我們需要創造一個相似物件時,這個方法很好用。
function Rabbit(name) {
  this.name = name;
  alert(name);
}

let rabbit = new Rabbit("White Rabbit");

let rabbit2 = new rabbit.constructor("Black Rabbit");

// 改變函式的 prototype 屬性,constructor 屬性會消失
function Rabbit() {}
Rabbit.prototype = {
  jumps: true
};

let rabbit = new Rabbit();
alert(rabbit.constructor === Rabbit); // false

// 為了保留 constructor 屬性,可以增加/移除屬性到 prototype 屬性
function Rabbit() {}

// Not overwrite Rabbit.prototype totally
// just add to it
Rabbit.prototype.jumps = true
// the default Rabbit.prototype.constructor is preserved

// 可以手動創造 constructor 屬性
Rabbit.prototype = {
  jumps: true,
  constructor: Rabbit
};

// now constructor is also correct, because we added it

Last updated