所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法。
在前面的章节中我们学会了如何使用对象的构造器(constructor):
实例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
我们也知道在一个已存在构造器的对象中是不能添加新的属性:
实例
Person.nationality = "English";
要添加一个新的属性需要在在构造器函数中添加:
实例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
|