Javascript也是面向對象的語言,但它是一種基于原型Prototype的語言,而不是基于類的語言。在Javascript中,類和對象看起來沒有太多的區別。
什么是prototype:
function定義的對象有一個prototype屬性,prototype屬性又指向了一個prototype對象,注意prototype屬性與prototype對象是兩個不同的東西,要注意區別。在prototype對象中又有一個constructor屬性,這個constructor屬性同樣指向一個constructor對象,而這個constructor對象恰恰就是這個function函數本身。 是不是很繞?用偽代碼表示如下:
var function{prototype:prototype{constructor:constructor == function}}還不明白?看圖吧:

prototype的作用:
這個prototype到底有什么作用呢?看下面的例子:
function jb51(){}jb51.prototype.name = "a";var test = new jb51();alert(test.name)//"a";奇怪吧,明明沒有為test設置name屬性,可是為什么會有值?
這就是prototype的功勞了,uw3c中prototype屬性中的name對象,在uw3c被new構造函數之后,被繼承到了對象test的屬性中。接著看:
var name = "js";function jb51(name){alert(this.name);//"css"}jb51.prototype.name = "css";var test = new jb51();test()為什么alert的值不是“js”?這個過程大致如下:
var test={};uw3c.call(test);第一步是建立一個新對象(test)。
第二步將該對象(test)內置的原型對象設置為構造函數(就是uw3c)prototype 屬性引用的那個原型對象。
第三步就是將該對象(test)作為this 參數調用構造函數(就是uw3c),完成成員設置等初始化工作。
其中第二步中出現了一個新名詞就是內置的原型對象,注意這個新名詞跟prototype對象不是一回事, 為了區別我叫它inobj,inobj就指向了函數uw3c的prototype對象。在uw3c的prototype對象中出現的任何屬性或者函數都可以在test對象中直接使用,這個就是JS中的原型繼承了。
通常,這樣創建一個對象:
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的所有實例都擁有呢?
--使用Prototypefunction animal(){}animal.prototype.color= "green";var cat = new animal();var dog = new animal();console.log(cat.color);//greenconsole.log(dog.color);//green 通過Prototype不僅可以添加字段,還可以添加方法。
function animal(){}animal.prototype.color= "green";var cat = new animal();var dog = new animal();console.log(cat.color);//greenconsole.log(dog.color);//greenanimal.prototype.run = funciton(){console.log("run");}dog.run(); 原來通過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為對象定義屬性或方法,還可以通過對象的構造函數來定義類的屬性或方法。
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定義一個類的字段和行為。
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屬性添加的字段或方法所有對象實例是共享的。
新聞熱點
疑難解答