JavaScript defines property usage instances for objects through prototype

  • 2020-05-17 04:49:47
  • OfStack

This example demonstrates the use of JavaScript to define properties for objects through prototype. Share with you for your reference. The specific analysis is as follows:

The JS code below defines the movie object. In the process of using the object, prototype is used to add isComedy property to the object. object.isComedy can be directly used when calling the object, which is very convenient.


<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>

I hope this article has been helpful to your javascript programming.


Related articles: