JavaScript emulates Java class inheritance

Source: Internet
Author: User

JavaScript inherits a class in the form of prototype inheritance (JavaScript does not have the concept of class, for the time being), but some programmers who have used Java may be accustomed to using classic class inheritance, but JavaScript primitives do not support this approach and therefore need to be implemented manually. This is accomplished by defining a function that defines a class (DefineClass), which is more comfortable to test. Because JavaScript does not have access modifiers, use closures if you need to use a private member.

1 /*simple method of object expansion2  */3Mergefunction(target, origin) {4      for(varAttributeinchorigin) {5         if(Origin.hasownproperty (attribute)) {6Target[attribute] =Origin[attribute];7         }8     }9 },TenDefineClass:functionDefineClass (constructor, parent, properties, statics, Issingleton) { One  A     /*If for singleton mode, save the instance and return this instance in a later call -      */ -     if(Issingleton) { the         varOldconstructor =Constructor, - instance; -constructor =function () { -             if(instance)returninstance; +Oldconstructor.apply ( This, arguments); -Instance = This; +         } A     } at  -     /*sets the prototype property, which means that the prototype property of the passed-in constructor is overwritten - * Important: The parent needs to detect parameters inside, -      */ -Constructor.prototype = parent?Newparent (): {}; -  in     /*copy your own properties into the prototype - * Copy the static property into the constructor, which means that the static property of the parent will not be inherited to      */ + Lang.merge (Constructor.prototype, properties); - Lang.merge (constructor, statics); the  *     /*change the constructor to the current constructor $ * Retain the parent's referencePanax Notoginseng      */ -Constructor.prototype.constructor =constructor; theConstructor.prototype.parent =parent; +Constructor.parent =parent; A  the     /*borrowing a parent class function +      */ -Constructor.borrow =function(methodName, context, args) { $         varoldparent; $  -         if(typeofMethodName = = = "Object") { -args =context; theContext =MethodName; -         }Wuyi  theOldparent =context.parent; -Context.parent =parent; Wu  -         if(typeofMethodName = = = "string") { AboutConstructor.prototype[methodname].apply (context, args | | []); $}Else { -Constructor.apply (context, args | | []); -         } -  AContext.parent =oldparent; +     }; the     returnconstructor; -}

When used, the parent class is so defined

1 varBody = Lang.defineclass (function(x, Y, shapes, sprites, detection) {2     /*because the class definition function creates the parent class instance as a prototype of the subclass, the parameter must be detected3 * If there are no arguments, it is equivalent to calling the parent class's default constructor4      */5     if(arguments.length) {6         /*using the parent class method7          */8          This. Parent.borrow ( This, arguments);9 Ten         /*non-basic type put in a constructor instead of a prototype One          */ A          This. _tasks = []; -     } - }, Object, { the_distance:0, -SetX:function(x) {}, -Sety:function(y) {} - }, { +Type: ' Base ' -});

Inherit body

1 varNinja = Lang.defineclass (function(){2      This. Parent.borrow ( This, arguments);3 }, Body, {4_status:1,5SetStatus:function(x) {6         /*using the parent class method7          */8          This. Parent.borrow (' SetStatus ', This, arguments);9     }Ten}, {});

Note that you cannot use this method to inherit built-in objects such as array, and if you want to extend the functionality of an array by defining a class, there will be a problem when calling some of the methods of array, such as the array returned by Concat directly contains two objects instead of the elements in two objects. The reason is that although the prototype chain of a subclass contains Array.prototype, it is not constructed directly by an array, and may not be executed in the original manner when some methods are called.

JavaScript emulates Java class inheritance

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.