萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JavaScript通過prototype給對象定義屬性用法實例

JavaScript通過prototype給對象定義屬性用法實例

 這篇文章主要介紹了JavaScript通過prototype給對象定義屬性用法,實例分析了prototype的功能及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下

   

本文實例講述了JavaScript通過prototype給對象定義屬性的用法。分享給大家供大家參考。具體分析如下:

下面的JS代碼定義了movie對象。在使用對象的過程中又通過prototype給對象添加了isComedy屬性,調用的時候直接使用object.isComedy即可,非常方便。

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <script type="text/javascript"> <!-- function movieToString() { return("title: "+this.title+" director: "+this.director); } function movie(title, director) { this.title = title; this.director = director || "unknown"; //if null assign to "unknown" this.toString = movieToString; //assign function to this method pointer } var officeSpace = new movie("OfficeSpace"); var narnia = new movie("Narnia","Andrew Adamson"); movie.prototype.isComedy = false; //add a field to the movie's prototype document.write(narnia.toString()); document.write("<br />Narnia a comedy? "+narnia.isComedy); officeSpace.isComedy = true; //override the default just for this object document.write("<br />Office Space a comedy? "+officeSpace.isComedy); //--> </script>

希望本文所述對大家的javascript程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved