1. 程式人生 > 其它 >用prototype擴充套件和繼承物件-JavaScript入門基礎(017)

用prototype擴充套件和繼承物件-JavaScript入門基礎(017)

技術標籤:JavaScriptjavascriptjquery

擴充套件物件:

可以使用prototype快速的新增屬性和方法。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script>        function Person(name) {            this.name = name;            this.info = "this person is called " + this.name;
this.showInfo = function () { alert(this.info); } } var person1 = new Person('Adam'); var person2 = new Person("Eve"); Person.prototype.sayHello = function () { alert(this.name + " says hello"); }
</script></head><body> <input type="button" value="show info on adam" onclick="person1.showInfo()"> <input type="button" value="show info on Eve" onclick="person2.showInfo()"> <input type="button" value="say hello adam" onclick="person1.sayHello()">
<input type="button" value="say hello Eve" onclick="person2.sayHello()"></body></html>

當我們需要給物件增加新的方法或者新的屬性時,可以使用prototype增加即可。

繼承物件:

JavaScript模擬實現繼承的方式也是使用關鍵字prototype。

首先我們先宣告一個物件:

function Pet() {  this.animal = "";  this.name = "";this.setAnimal= function(newAnimal){  this.animal = newAnimal;}this.setName = function(newName){  this.name = newName;}}

我們可以宣告這個類定義的物件:

varmyCat = new Pet();myCat.setAnimal = "cat";myCat.setName = "Sylvester";

此時,如果我們需要在建立一個物件,是重頭開始建立嗎,我們可以這樣

function Dog {  this.breed = "";this.setBreed=function(newBreed){this.breed=newBreed;}}Dog.prototype = new Pet();
varmyDog=newDog();myDog.setName("Alan");myDog.setBreed("Greyhound");alert(myDog.name+"isa"+myDog.breed);

通過以上操作,我們就可以將pet類的屬性和方法,由Dog類繼承下來。

如果大家有一定的其他程式碼經驗,一定會覺得,為什麼JavaScript在宣告類的時候,要用function,很不習慣,也有點雲裡霧裡的。

經過一定時間的發展後,JavaScript意識到了這點,所以也同其他程式語言一樣引入了class關鍵字。

class Pet {  constructor(animal,name)   {this.animal=animal;this.name=name;  }    setAnimal(newAnimal)  {this.animal=newAnimal;  }  setName(newName){  this.name = newName;}}

用class宣告類,就讓人比較好理解了,另外還特意增加了建構函式,雖然不是同類名的建構函式,而是固定了一個關鍵字用來當做建構函式。

var myCat = new Pet("cat","Sylvester");myCat.setAnimal("cat");myCat.setName("Sylvester");

新增的getter和setter:

class Pet{  constructor(animal,name)  {    this.animal = animal;    this.name = name;  }  setAnimal(newAnimal){  this.animal = newAnimal;}setName(newName){  this.name = newName;}get name(){  return this._name;}set name(n){this._name = n;}}

在getter和setter中,name屬性加了一個下劃線,變成了_name。是為了防止get被重複呼叫造成死迴圈,特意使用_name來區分開。

var myCat = new Pet("cat","sylvester");alert(myCat.name);myCat.setName("THOMAS");alert(myCat.name);

物件繼承extends和super:

class Pet{  this.name = "";  this.setName=function(newName) {  this.name = newName;}constructor(name){this.name = name;}}
classDogextends Pet {  this.breed = "";  this.setBreed=function(newBreed)  {this.breed=newBreed;  }  constructor(name,breed){  super(name);this.breed=breed;}}
varmyDog=newDog("Alan","greyhound");alert(myDog.name+"isa"+myDog.breed);


圖片