JavaScript 对象原型
所有 JavaScript 对象都从原型继承属性和方法。
在前一章里,我们学到了如何使用对象构造器:
实例
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");
亲自试一试 »
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");
我们已经认识到,您无法为已有的对象构造器添加新属性:
如需向构造器添加一个新属性,则必须把它添加到构造器函数:
实例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
亲自试一试 »
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
原型继承
所有 JavaScript 对象都从原型继承属性和方法。
Date
日期对象继承自Date.prototype
Array
数组对象继承自Array.prototype
Person
对象继承自Person.prototype
Object.prototype
位于原型继承链的顶端:
Date
对象, Array
对象, 和 Person
对象都继承自 Object.prototype
。
向对象添加属性和方法
有时,您希望向所有给定类型的已有对象添加新属性(或方法)。
有时,您希望向对象构造器添加新属性(或方法)。
使用 >prototype 属性
JavaScript prototype
属性允许您为对象构造器添加新属性:
实例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
亲自试一试 »
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
JavaScript prototype
属性也允许您为对象构造器添加新方法:
实例
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
亲自试一试 »
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
请只修改您自己的原型。绝不要修改标准 JavaScript 对象的原型。