Home >Web Front-end >JS Tutorial >An in-depth exploration of the definition and usage of JS classes

An in-depth exploration of the definition and usage of JS classes

高洛峰
高洛峰Original
2016-12-05 10:51:281017browse

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(&#39;nihao&#39;);
};
Anim.prototype.start = function() {
  alert(&#39;start&#39;);
};
Anim.prototype.stop = function() {
   alert(&#39;stop&#39;);
};
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(&#39;nihao&#39;);
};
Anim.prototype = {
 start: function() {
  alert(&#39;start&#39;);
 },
 stop: function() {
  alert(&#39;stop&#39;);
 }
};
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(&#39;nihao&#39;);
};
Function.prototype.method = function(name, fn) { // 这个很有作用
 this.prototype[name] = fn;
};
Anim.method(&#39;start&#39;, function() {
 alert(&#39;start&#39;);
});
Anim.method(&#39;stop&#39;, function() {
 alert(&#39;stop&#39;);
});
var myAnim = new Anim();
myAnim.start();
myAnim.stop();
</script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn