Introduction to a simple JavaScript framework _ basic knowledge

Source: Internet
Author: User
This article mainly introduces a simple JavaScript framework, which helps beginners understand the creation and Inheritance of JS classes. If you need it, refer to the following when writing the work-in-progress JavaScript book, I spent quite some time on the javascript inheritance system and studied various methods to simulate classic inheritance. Among these technical solutions, I highly recommend the implementation of base2 and Prototype.

From these solutions, we should be able to develop a framework with its ideological connotation. This framework must be simple, reusable, easy to understand, and independent, among which simplicity and availability are the focus. The following is an example:

var Person = Class. extend ( { init: function (isDancing ) {  this. dancing = isDancing; }, dance: function ( ) {  return this. dancing; }} );var Ninja = Person.extend({ init: function(){  this._super( false ); }, dance: function(){  // Call the inherited version of dance()  return this._super(); }, swingSword: function(){  return true; }});var p = new Person(true);p.dance(); // => truevar n = new Ninja();n.dance(); // => falsen.swingSword(); // => true// Should all be truep instanceof Person && p instanceof Class &&n instanceof Ninja && n instanceof Person && n instanceof Class

Pay attention to the following points:

  • The constructor must be simple (implemented through the init function ),
  • The new definition of analogy must inherit the existing class,
  • All 'class' inherit from the ancestor Class: Class. Therefore, to create a new Class, the Class must be a subclass of the Class,
  • The most challenging aspect is that the overwriting method of the parent class must be accessible (by configuring the context ).
  • In the preceding example, you can find that the init () and dance () Methods of the Person parent class are called through this. _ super.

Satisfied with the results: the class definition is structured to maintain a single inheritance, and the super class method can be called.

Simple class creation and inheritance

The following shows the implementation (easy to read and annotate), about 25 lines. Thank you for your suggestions.

/* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */// Inspired by base2 and Prototype( function ( ) { var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){};   // Create a new Class that inherits from this class Class.extend = function(prop) {  var _super = this.prototype;     // Instantiate a base class (but only create the instance,  // don't run the init constructor)  initializing = true;  var prototype = new this();  initializing = false;     // Copy the properties over onto the new prototype  for (var name in prop) {   // 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 that is the same method      // but on the super-class      this._super = _super[name];             // The method only need to be 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];  }     // The dummy class constructor  function Class() {   // All construction is actually done in the init method   if ( !initializing && this.init )    this.init.apply(this, arguments);  }     // Populate our constructed prototype object  Class.prototype = prototype;     // Enforce the constructor to be what we expect  Class.prototype.constructor = Class;  // And make this class extendable  Class.extend = arguments.callee;     return Class; };})();

Among them, "initialization (initializing/don't call init)" and "create _ super method" are the most difficult. Next, I will give a brief introduction to this, so that you can better understand its implementation mechanism.

Initialization

To illustrate the Inheritance Method of the original type of the function, we first look at the traditional implementation process, that is, pointing the prototype attribute of the subclass to an instance of the parent class. As follows:


function Person ( ) { }function Ninja ( ) { }Ninja. prototype = new Person ( );// Allows for instanceof to work:(new Ninja()) instanceof Person

However, the challenge here is that we only want to get the effect of 'instance' without the consequence of instance a Person and calling its constructor. To prevent this, set a bool parameter initializing in the Code. The value is true only when the parent class is instantiated and configured to the prototype attribute of the subclass. The purpose of this process is to distinguish between the real instantiation and the design inheritance of the two called constructors, and then call the init method in the real instantiation:

if ( !initializing ) this.init.apply(this, arguments);

It is worth noting that, because the init function may run code with a considerable amount of resources (such as connecting to the server and creating DOM elements, no one can predict ), therefore, it is necessary to make a distinction.

Super Method)

When inheritance is used, the most common requirement is that sub-classes can access the superclass overwriting method. In this implementation, the final solution is to provide a temporary method (. _ super), which points to the superclass method and can only be accessed in the subclass method.

var Person = Class. extend ( { init: function (isDancing ) {  this. dancing = isDancing; }} );var Ninja = Person.extend({ init: function(){  this._super( false ); }});var p = new Person(true);p.dancing; // => truevar n = new Ninja();n.dancing; // => false


Several steps are required to implement this function. First, we use extend to merge basic Person instances (class instances, we mentioned above) and literal objects (function parameters of Person. extend ). During the merge process, a simple check is performed: First, check whether the merged attributes are functions, for example, functions, and then check whether the overwritten attributes are also functions? If both checks are true, you need to prepare the _ super method for this attribute.

Note that an anonymous closure (the returned function object) is created here to encapsulate the added super method. Based on the need to maintain the running environment, we should. _ super (whether it exists or not) is saved for resetting after the function is run, which helps to cause unpredictable problems when the object pointer is the same name (not accidental loss of the Object Pointer.

Then, create a new _ super method. The method object only points to the override method in the superclass. Thank God, there is no need to make any changes to the _ super or change the scope, because the execution environment of the function will automatically change with the function calling object (the pointer this will point to the super class ).

Finally, call the literal object method. this may be used during method execution. _ super (). After the method is executed, reset attribute _ super back to its original state, and then return to exit the function.


There are many ways to achieve the same effect as above (I have seen that super is bound to itself, and then arguments. callee access), but it seems that this method can best reflect the features of availability and simplicity.

Among the many javascript-based prototype projects I have completed, I have published only this class inheritance implementation solution to share with you. In my opinion, concise code (easy to learn, easy to inherit, and less to download) needs to be proposed for discussion. Therefore, for those who learn javascript class construction and inheritance, this implementation scheme is a good start.

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.