The examples in this article analyze the definition and usage of JS classes. Share it with everyone for your reference, the details are as follows:
js can define its own class
It’s very interesting
<script type="text/javascript"> var Anim = function() { alert('nihao'); }; Anim.prototype.start = function() { alert('start'); }; Anim.prototype.stop = function() { alert('stop'); }; var myAnim = new Anim(); myAnim.start(); myAnim.stop(); </script>
Anim is a class, and nihao will pop up during initialization.
It has two methods, one is the start method and the other is the stop method.
When using it, just use 'dot' to call it.
<script type="text/javascript"> var Anim = function() { alert('nihao'); }; Anim.prototype = { start: function() { alert('start'); }, stop: function() { alert('stop'); } }; var myAnim = new Anim(); myAnim.start(); myAnim.stop(); </script>
Another way of definition, the same effect as above.
The third type,
<script type="text/javascript"> var Anim = function() { alert('nihao'); }; Function.prototype.method = function(name, fn) { // 这个很有作用 this.prototype[name] = fn; }; Anim.method('start', function() { alert('start'); }); Anim.method('stop', function() { alert('stop'); }); var myAnim = new Anim(); myAnim.start(); myAnim.stop(); </script>