sprewell20051116 / JavascriptCourse

讀書會提出問題的平台
0 stars 2 forks source link

Prototype 的用處 #15

Open sprewell20051116 opened 7 years ago

sprewell20051116 commented 7 years ago

看起來應該就是做 Class 的擴展的方便用法 課堂中使用的 Wizard Class

function Wizards (name, house, pet) {
  this.name = name;
  this.house = house;
  this.pet = pet;
  this.greet = () => `I'm ${this.name} from ${this.house}`;
}

後面想要在這個 Class 中新增一個 Member,可以不用直接去更動到 Wizard Class 的類別宣告,而是使用 prototype 的這個關鍵字來作為擴展

Wizards.prototype.pet_name;
let Harry = new Wizards("Harry Potter", "Gryffindor", "Owl");
Harry.pet_name = "Hedwig"
console.log(Harry); 
//Wizards {name: "Harry Potter", house: "Gryffindor", pet: "Owl", pet_name: "Hedwig", greet: ƒ}
sprewell20051116 commented 7 years ago

prototype 的這個關鍵字也可以拿來擴展 Class 的 Method

Wizards.prototype.info = function() {
  return `I have a ${this.pet} name ${this.pet_name}`
};
sprewell20051116 commented 7 years ago

http://www.codedata.com.tw/javascript/essential-javascript-15-prototype/