JavaScript 对象原型
All JavaScript objects inherit properties and methods from a prototype.
In the previous chapter we learned how to use an object constructor:
例子
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
亲自尝试 »
We also learned that you can not add a new property to an existing object constructor:
To add a new property to a constructor, you must add it to the constructor function:
例子
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 a prototype:
Date
objects inherit fromDate.prototype
Array
objects inherit fromArray.prototype
Person
objects inherit fromPerson.prototype
这 Object.prototype
is on the top of the prototype inheritance chain:
Date
objects, Array
objects, and Person
objects inherit from Object.prototype
.
Adding Properties and Methods to Objects
Sometimes you want to add new properties (or methods) to all existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object constructor.
Using the prototype Property
JavaScript prototype
property allows you to add new properties to object constructors:
例子
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
亲自尝试 »
JavaScript prototype
property also allows you to add new methods to objects constructors:
例子
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;
};
亲自尝试 »
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.