JavaScript Object Prototype
- Previous Page JS Object Constructors
- Next Page JS Object References
All JavaScript objects inherit properties and methods from prototypes.
In the previous chapter, we learned how to useObject constructor:
Instances
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");
We have realized that youUnable toAdd new properties to the constructor of existing objects:
Instances
Person.nationality = "English";
If you need to add a new property to a constructor, you must add it to the constructor function:
Instances
function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; this.nationality = "English"; }
Prototype inheritance
All JavaScript objects inherit properties and methods from prototypes.
Date objects inherit from Date.prototype. Array objects inherit from Array.prototype. Person objects inherit from Person.prototype.
Object.prototype is at the top of the prototype inheritance chain:
Date objects, array objects, and Person objects all inherit from Object.prototype.
Adding properties and methods to objects
Sometimes, you may want to add new properties (or methods) to all existing objects of a given type.
Sometimes, you may want to add new properties (or methods) to the object constructor.
Usage Prototype
Properties
The JavaScript prototype property allows you to add new properties to the object constructor:
Instances
function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.nationality = "English";
The JavaScript prototype property also allows you to add new methods to the object constructor:
Instances
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 对象的原型。
- Previous Page JS Object Constructors
- Next Page JS Object References