use prototype property

 

先前提到不可以直接在 constructor 本體上添加屬性的範例

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather.firstName);
console.log(myMother.firstName);

Person.nationality = "English";
console.log(myFather.nationality);

 

現在可利用 prototype 屬性,就可以在 constructor 本體上添加屬性了。

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather.firstName);
console.log(myMother.firstName);

Person.prototype.nationality = "English";
console.log(myFather.nationality);

 

Tip:在使用 prototype 時請小心,不要任意去修改 constructor 本體。