首頁 >web前端 >js教程 >JavaScript透過prototype為物件定義屬性用法實例_javascript技巧

JavaScript透過prototype為物件定義屬性用法實例_javascript技巧

WBOY
WBOY原創
2016-05-16 16:08:081180瀏覽

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

下面的JS程式碼定義了movie物件。在使用物件的過程中又透過prototype為物件添加了isComedy屬性,呼叫的時候直接使用object.isComedy即可,非常方便。

<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&#63; "+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this object
document.write("<br />Office Space a comedy&#63; "+officeSpace.isComedy);
//-->
</script>

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn