Home > Web Front-end > JS Tutorial > Detailed explanation of javascript class definitions, attributes, and method calling techniques with examples

Detailed explanation of javascript class definitions, attributes, and method calling techniques with examples

伊谢尔伦
Release: 2017-07-27 13:39:58
Original
1658 people have browsed it

js can define its own class


<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>
Copy after login

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, use 'dot' to call it directly.


<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>
Copy after login

Another definition method, the same effect as above.


<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>
Copy after login

The above is the detailed content of Detailed explanation of javascript class definitions, attributes, and method calling techniques with examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template