全部JavaScript对象都从原型继承属性和方法。javascript
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h2>JavaScript 对象</h2>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); document.getElementById("demo").innerHTML = "My father is " + myFather.age + ". My mother is " + myMother.age; </script> </body> </html>
咱们还了解到,您没法向现有对象构造函数添加新属性:html
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript对象</title>
<body>
<h2>JavaScript对象</h2>
<p>您没法向构造函数添加新属性。</p>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } Person.nationality = "English"; var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); document.getElementById("demo").innerHTML = "The nationality of my father is " + myFather.nationality; </script> </body> </html>
要向构造函数添加新属性,必须将其添加到构造函数:java
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript对象</title>
<body>
<h2> JavaScript对象</h2>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; this.nationality = "English"; } var myFather = new Person("John", "Doe", 50, "blue"); var myMother = new Person("Sally", "Rally", 48, "green"); document.getElementById("demo").innerHTML = "我父亲的国籍是 " + myFather.nationality + ". 我母亲的国籍是: " + myMother.nationality; </script> </body> </html>
全部JavaScript对象都从原型继承属性和方法:函数
Object.prototype位于原型继承链的顶部:Date对象,Array对象和Person对象继承自Object.prototype。this
* Date 对象继承自 Date.prototype
* Array 对象继承自 Array.prototype
* Person 对象继承自 Person.prototypespa
# 向对象添加属性和方法prototype
有时,您但愿向给定类型的全部现有对象添加新属性(或方法)。有时您想要向对象构造函数添加新属性(或方法)。code
JavaScript prototype属性容许您向对象构造函数添加新属性:htm
function Person(first, last, age, eyecolor) {
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; };