Js object-oriented programming, four methods of defining classes

Source: Internet
Author: User


Method 1:

/* Anim class. */var Anim = function() {  ...};Anim.prototype.start = function() {  ...};Anim.prototype.stop = function() {  ...};/* Usage. */var myAnim = new Anim();myAnim.start();...myAnim.stop();

Method 2:

/* Anim class, with a slightly different syntax for declaring methods. */var Anim = function() {   ...};Anim.prototype = {  start: function() {    ...  },  stop: function() {    ...  }};

Method 3:

/* Add a method to the Function class that can be used to declare methods. */Function.prototype.method = function(name, fn) {  this.prototype[name] = fn;};/* Anim class, with methods created using a convenience method. */var Anim = function() {   ...};Anim.method('start', function() {  ...});Anim.method('stop', function() {  ...});

Method 4:

/* This version allows the calls to be chained. */Function.prototype.method = function(name, fn) {    this.prototype[name] = fn;    return this;};/* Anim class, with methods created using a convenience method and chaining. */var Anim = function() {   ...};Anim.  method('start', function() {    ...  }).  method('stop', function() {    ...  });


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.