JavaScript prototype原型用法

JavaScript對象原型

全部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; };

更好的原型對象的文章

相關文章
相關標籤/搜索