JavaScript prototype原型用法

web全棧發表於2019-07-26

JavaScript物件原型
所有JavaScript物件都從原型繼承屬性和方法。


    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;

我們還了解到,您無法向現有物件建構函式新增新屬性:


    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;

要向建構函式新增新屬性,必須將其新增到建構函式:


    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;

原型繼承
所有JavaScript物件都從原型繼承屬性和方法:
Object.prototype位於原型繼承鏈的頂部:Date物件,Array物件和Person物件繼承自Object.prototype。


*   Date 物件繼承自 Date.prototype
*   Array 物件繼承自 Array.prototype
*   Person 物件繼承自 Person.prototype

向物件新增屬性和方法

有時,您希望向給定型別的所有現有物件新增新屬性(或方法)。有時您想要向物件建構函式新增新屬性(或方法)。

使用 原型 屬性

JavaScript prototype屬性允許您向物件建構函式新增新屬性:


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

更好的原型物件的文章

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69942367/viewspace-2651817/,如需轉載,請註明出處,否則將追究法律責任。

相關文章