The example in this article describes the use of JavaScript to define attributes for objects through prototype. Share it with everyone for your reference. The specific analysis is as follows:
The following JS code defines the movie object. In the process of using the object, the isComedy attribute is added to the object through the prototype. When calling, you can directly use object.isComedy, 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 will be helpful to everyone’s JavaScript programming design.