JavaScript 对象原型
内容摘要
所有 JavaScript 对象都从原型继承属性和方法。
文章正文
所有 JavaScript 对象都从原型继承属性和方法。
请只修改您自己的原型。绝不要修改标准 JavaScript 对象的原型。
在前一章里,我们学到了如何使用对象构造器:
实例
1 2 3 4 5 6 7 8 | function Person(first, last, age, eyecolor) { this .firstName = first; this .lastName = last; this .age = age; this .eyeColor = eyecolor; } var myFather = new Person( "Bill" , "Gates" , 62, "blue" ); var myMother = new Person( "Steve" , "Jobs" , 56, "green" ); |
我们已经认识到,您无法为已有的对象构造器添加新属性:
实例
1 | Person.nationality = "English" ; |
如需向构造器添加一个新属性,则必须把它添加到构造器函数:
实例
1 2 3 4 5 6 7 | function Person(first, last, age, eyecolor) { this .firstName = first; this .lastName = last; this .age = age; this .eyeColor = eyecolor; this .nationality = "English" ; } |
原型继承
所有 JavaScript 对象都从原型继承属性和方法。
日期对象继承自 Date.prototype。数组对象继承自 Array.prototype。Person 对象继承自 Person.prototype。
Object.prototype 位于原型继承链的顶端:
日期对象、数组对象和 Person 对象都继承自 Object.prototype。
向对象添加属性和方法
有时,您希望向所有给定类型的已有对象添加新属性(或方法)。
有时,您希望向对象构造器添加新属性(或方法)。
使用 prototype 属性
JavaScript prototype 属性允许您为对象构造器添加新属性:
实例
1 2 3 4 5 6 7 | function Person(first, last, age, eyecolor) { this .firstName = first; this .lastName = last; this .age = age; this .eyeColor = eyecolor; } Person.prototype.nationality = "English" ; |
JavaScript prototype 属性也允许您为对象构造器添加新方法:
实例
1 2 3 4 5 6 7 8 9 | 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; }; |
请只修改您自己的原型。绝不要修改标准 JavaScript 对象的原型。
代码注释