首页 >web前端 >js教程 >JavaScript通过prototype给对象定义属性用法实例_javascript技巧

JavaScript通过prototype给对象定义属性用法实例_javascript技巧

WBOY
WBOY原创
2016-05-16 16:08:081181浏览

本文实例讲述了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