Simple JavaScript inheritance--a minimalist JS inheritance library

Source: Internet
Author: User
Tags jquery library

Object oriented

Several important features of object-oriented thinking (requirements for classes):

Abstraction-encapsulation, information hiding (internally implemented methods and data hiding, defining open interfaces)

Inheritance-subclasses can use the resources of the parent class, and can customize their own resources, including methods and data

Polymorphic-Overloaded (function with the same name), overwrite (overriding parent-class function on the basis of inheritance)

JS and Object-oriented

JavaScript uses prototype to implement class inheritance, non-classic object-oriented language classes, and the use of different methods, resulting in more difficult to use.

Please refer to the master's "in-depth understanding of JavaScript prototypes and closures series" http://www.cnblogs.com/wangfupeng1988/p/4001284.html

So various libraries provide their own implementation of the class library, for example:

1. jquery Class Create:https://github.com/protonet/jquery-class-create

Use Class.create to create a utility class, the constructor of an instance, with the disadvantage of using the jquery library

<pre>
// properties are directly passed to `create` method  var Person = Class.create({    initialize: function(name) {      this.name = name;    },    say: function(message) {      return this.name + ‘: ‘ + message;    }  });    // when subclassing, specify the class you want to inherit from  var Pirate = Class.create(Person, {    // redefine the speak method    say: function($super, message) {      return $super(message) + ‘, yarr!‘;    }  });    var john = new Pirate(‘Long John‘);  john.say(‘ahoy matey‘);  // -> "Long John: ahoy matey, yarr!"
</pre>

2, Prototypejs:http://prototypejs.org/learn/class-inheritance

As a function of the Prototypejs library, the use is consistent with the jquery class create interface.

This library also provides an elegant interface for Ajax and DOM, eliminating the complexity of client development.

These two libraries either rely on other libraries, or their own library function complex, volume is large, so the need to use alone is not satisfied.

This article describes a library that does not rely on any library, and implements only the class inheritance, a standalone library developed by the Great God: John resig http://ejohn.org/

Simple JavaScript Inheritance

Simple JavaScript Inheritance

This library's official website is

http://ejohn.org/blog/simple-javascript-inheritance/

The goal of the author is simple-easy to understand, reusable-not dependent on other libraries, using examples:

<pre>

  1. var person = class.extend ({

  2. Init:function (isdancing) {

  3. this.dancing = isdancing;

  4. },

  5. Dance:function () {

  6. return this.dancing;

  7. }

  8. });

  9. var Ninja = Person.extend ({

  10. Init:function () {

  11. This._super (FALSE);

  12. },

  13. Dance:function () {

  14. Call the inherited version of Dance ()

  15. return This._super ();

  16. },

  17. Swingsword:function () {

  18. return true;

  19. }

  20. });

  21. var p = new Person (true);

  22. P.dance (); = True

  23. var n = new Ninja ();

  24. N.dance (); = False

  25. N.swingsword (); = True

  26. Should all is true

  27. P instanceof person && p instanceof Class &&

  28. n instanceof Ninja && n instanceof person && n instanceof Class

</pre>

Implementation notes:

1. Creating a constructor must be simple, and the constructor provides only the Init initialization method.

2. To create a new class, you must extend an existing class to invoke extend.

3. All inheritance with the only ancestor Class. The new class created must be a subclass of class.

4. A method with the same name that accesses the parent class in the subclass (that is, overwritten) must be provided. A method with the same name as the parent class is called through the This.super child class with the same name.

Implementation Essentials

Implementation code:

<pre>

  1. /* Simple JavaScript inheritance

  2. * by John Resig http://ejohn.org/

  3. * MIT Licensed.

  4. */

  5. Inspired by Base2 and Prototype

  6. (function () {

  7. var initializing = false, Fntest =/xyz/.test (function () {xyz;})? /\b_super\b/:/.*/;

  8. The base Class implementation (does nothing)

  9. This. Class = function () {};

  10. Create a new class that inherits from this class

  11. Class.extend = function (prop) {

  12. var _super = This.prototype;

  13. Instantiate a base class (but only create the instance,

  14. Don ' t run the Init constructor)

  15. initializing = true;

  16. var prototype = new This ();

  17. initializing = false;

  18. Copy the properties over onto the new prototype

  19. for (var name in prop) {

  20. Check if we ' re overwriting an existing function

  21. Prototype[name] = typeof Prop[name] = = "function" &&

  22. typeof _super[name] = = "function" && fntest.test (Prop[name])?

  23. (function (name, FN) {

  24. return function () {

  25. var tmp = This._super;

  26. Add a new _super () method is the same method

  27. But on the Super-class

  28. This._super = _super[name];

  29. The method is need to being bound temporarily, so we

  30. Remove it when we ' re done executing

  31. var ret = fn.apply (this, arguments);

  32. This._super = tmp;

  33. return ret;

  34. };

  35. }) (name, Prop[name]):

  36. Prop[name];

  37. }

  38. The Dummy class constructor

  39. function Class () {

  40. All construction is actually do in the Init method

  41. if (!initializing && this.init)

  42. This.init.apply (this, arguments);

  43. }

  44. Populate our constructed prototype object

  45. Class.prototype = prototype;

  46. Enforce the constructor to being what we expect

  47. Class.prototype.constructor = Class;

  48. And make this class extendable

  49. Class.extend = Arguments.callee;

  50. return Class;

  51. };

  52. })();

</pre>

Points:

1. Initialize init in call Xx.extend{init:function () {}}

  • The Dummy class constructor

  • function Class () {

  • All construction is actually do in the Init method

  • if (!initializing && this.init)

  • This.init.apply (this, arguments);

  • }

  • 2. Subclasses access the parent class's function with the same name through This._super, for example:

      1. var person = class.extend ({

      2. Init:function (isdancing) {

      3. this.dancing = isdancing;

      4. }

      5. });

      6. var Ninja = Person.extend ({

      7. Init:function () {

      8. This._super (FALSE);

      9. }

      10. });

      11. var p = new Person (true);

      12. p.dancing; = True

      13. var n = new Ninja ();

      14. n.dancing; = False

    As follows, the son has this function, and the father also has this function of the same name, when the function address is recorded in This._super.

  • Check if we ' re overwriting an existing function

  • Prototype[name] = typeof Prop[name] = = "function" &&

  • typeof _super[name] = = "function" && fntest.test (Prop[name])?

  • (function (name, FN) {

  • return function () {

  • var tmp = This._super;

  • Add a new _super () method is the same method

  • But on the Super-class

  • This._super = _super[name];

  • The method is need to being bound temporarily, so we

  • Remove it when we ' re done executing

  • var ret = fn.apply (this, arguments);

  • This._super = tmp;

  • return ret;

  • };

  • }) (name, Prop[name]):

  • Prop[name];

  • }

  • Simple JavaScript inheritance--a minimalist JS inheritance library

    Related Article

    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.