Open sprewell20051116 opened 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 的這個關鍵字來作為擴展
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: ƒ}
prototype 的這個關鍵字也可以拿來擴展 Class 的 Method
Wizards.prototype.info = function() { return `I have a ${this.pet} name ${this.pet_name}` };
http://www.codedata.com.tw/javascript/essential-javascript-15-prototype/
看起來應該就是做 Class 的擴展的方便用法 課堂中使用的 Wizard Class
後面想要在這個 Class 中新增一個 Member,可以不用直接去更動到 Wizard Class 的類別宣告,而是使用
prototype
的這個關鍵字來作為擴展