若把方法寫在建構式內部,每建立一個物件,就會產生一份新的函式。使用 prototype 可讓所有實例共用同一個方法。
var Person = function (name, age) {
this.name = name;
this.age = age;
};
Person.prototype.Introduce = function () {
alert(this.name + ' ' + this.age);
};
這樣 person1 與 person2 的 Introduce 會指向同一個原型方法,能減少記憶體浪費。