原型模式可讓多個物件實例共用屬性與方法。若每個實例都重複建立相同函式,會浪費記憶體;透過 prototype 可讓所有實例共享同一份方法。
function Person() {}
Person.prototype.name = 'jack';
Person.prototype.age = 10;
Person.prototype.sayInformation = function() {
console.log('my name is ' + this.name + ' age is ' + this.age);
};
const person1 = new Person();
person1.sayInformation();
person1.name = 'Greg';
console.info(person1.name);
delete person1.name;
console.info(person1.name);
const person2 = new Person();
console.info(person1.hasOwnProperty('name'));
console.info(person1.sayInformation === person2.sayInformation);
hasOwnProperty 可用來判斷屬性屬於實例還是原型。若屬性只在原型上,所有實例都能共用;若實例自己定義同名屬性,則會優先使用實例屬性。