Javascript也是面向對象的語言,但它是一種基於原型Prototype的語言,而不是基於類的語言。在Javascript中,類和對象看起來沒有太多的區別。數組
一般,這樣建立一個對象:ide
function person(name){ this.sayHi = function(){ alert('hi ' + this.name); } this.name = name; } var p = new person("dan"); p.sayHi();
以上,使用new關鍵字,經過對象(函數也是特殊對象)建立一個對象實例。
在基於類的語言中,屬性或字段一般都是在類中事先定義好了,但在Javascript中,在建立對象以後還能夠爲類添加字段。函數
function animal(){} var cat = new animal(); cat.color = "green";
以上,color這個字段只屬於當前的cat實例。
對於後加的字段,若是想讓animal的全部實例都擁有呢?
--使用Prototypethis
function animal(){} animal.prototype.color= "green"; var cat = new animal(); var dog = new animal(); console.log(cat.color);//green console.log(dog.color);//green
經過Prototype不只能夠添加字段,還能夠添加方法。spa
function animal(){} animal.prototype.color= "green"; var cat = new animal(); var dog = new animal(); console.log(cat.color);//green console.log(dog.color);//green animal.prototype.run = funciton(){ console.log("run"); } dog.run();
原來經過prototype屬性,在建立對象以後還能夠改變對象的行爲。
好比,能夠爲數組這個特殊對象添加一個方法。prototype
Array.prototype.remove = function(elem){ var index = this.indexof(elem); if(index >= 0){ this.splice(index, 1); } } var arr = [1, 2, 3] ; arr.remove(2);
除了經過prototype爲對象定義屬性或方法,還能夠經過對象的構造函數來定義類的屬性或方法。code
function animal(){ this.color = "green"; this.run = function(){ console.log("run"); } } var mouse = new animal(); mouse.run();
以上作法的也能夠讓全部的animal實例共享全部的字段和方法。而且還有一個好處是能夠在構造函數中使用類的局部變量。對象
function animal(){ var runAlready = false; this.color = "green"; this.run = funciton(){ if(!runAlreadh){ console.log("start running"); } else { console.log("already running") } } }
其實,一個更加實際的作法是把經過構造函數結合經過prototype定義一個類的字段和行爲。blog
function animal(){ var runAlready = false; this.run = function(){ if(!runAlready){ console.log('i am running'); } else { console.log("i am already running"); } } } animal.prototype.color = ''; animal.prototype.hide = funciton(){ console.log(""); } var horse = new animal(); horse.run(); horse.hide();
Prototype容許咱們在建立對象以後來改變對象或類的行爲,而且這些經過prototype屬性添加的字段或方法全部對象實例是共享的。ip