JavaScript Inheritance Learning (i)

Source: Internet
Author: User

Many of the online JavaScript inheritance, here is not explained in detail, need, please own degree Niang or Valley father.


Before doing Cocos2d-js's game, found that it has a very interesting way of inheriting.

The form is as follows:

var A = cc. Class.extend ({//a series of functions et        ctor:function () {               ///This._super points to the ctor method of the father, unknown Li               this._super ();}        );

So studied, there are a few points to note:

1. function.tostring will return the entire function's definition string
2, Str.indexof method, there are two parameters, the first is a string, the second is the beginning of the position of the check, it first match on the end of the
3, its This._super method, is through matching or closure rewrite , get out of


So, try to do it yourself, to achieve:

function Class () {};//compilesuper is used in some specific cases, however, it saves memory space, and if debugging is not required, you can enable this inheritance Class.compilesuper = function (Fnstr,  FnName) {//Find the FN parameter var Pstart = Fnstr.indexof ("("), Pend = Fnstr.indexof (")"), var params = Fnstr.slice (Pstart + 1, pend);// Start with the FN body to find var str = fnstr.substring (Fnstr.indexof ("{") + 1, Fnstr.lastindexof ("}"));//replace this._super for This.super[name ]//Cocos2d-js is implemented by a for loop, but because there is more than one super field recorded here, there is no trouble with it ~var keyName = "this.super." + Fnname;str = str.replace (/this. _super/g, "This.super &&" + keyName + "&&" + keyName);//Returns a new function (params, str); Class.extend = function (proto) {var _super = this.prototype;function MyClass () {This.ctor && this.ctor.apply ( this, arguments);}; var fn = myclass.prototype;//below this for loop, if re-packaged, you can implement multi-parameter form ~, experiment, not too much consideration for (Var key in Proto) {//current Itemvar item = Proto[key ];//if both the parent and the current are functions, there is an inheritance relationship var Issuperfunc = "function" = = typeof _super[key], Isfunc = "function" = = typeof item;if (Isfunc & amp;& issuperfunc) {//implement inheritance, package oneSuper method, if there is a field such as _super, then compile var reg =/\b_super\b/, itemstr = item.tostring (), if (Reg.test (ITEMSTR)) {//have _super method, The Super method is compiled//But not a bit of debugging, you can consider in other modes "If you do not want to be debugged by others ...", using this compilation//Here is the main experiment, do not operate the//fn[key] = Class.compilesuper (ITEMSTR, key);//Discard compile method, use closure fn[key] = (function (key, proto) {return function () {var tmp = this._super;//This sentence relies on fn.super = _super; This._super = This.super[key];var res = item.apply (this, arguments); this._super = Tmp;return res;};}) (Key, item);} Else{fn[key] = Item;}} Else{fn[key] = item;}};/ /can find through super to parent class Fn.super = _super;myclass.extend = Fn.extend = Class.extend;return myClass;};


The implementation that matches the "recompile string" was discarded for reasons such as failure to debug, and closures were used.

But closures bring additional memory consumption, so if you're really on-line, it's best to use matching implementations.


Let's look at two examples:

var Myfirst = Class.extend ({constroctor:myfirst,ctor:function (name) {///) because the parent class, there is no ctor method, so This._super (name); Will error//this._super (name); Console.log (name);}}); var Mysecond = Myfirst.extend ({ctor:function (name, age) {/////Inherits Myfirst because Myfirst has ctor method, so This._super (name) works normally with this . _super (name); Console.log (age);}}); /FINAL data: var ss = new Mysecond ("Da Zong Xiong", 26);//output: da Zong Xian 26


The code looks pretty classy,

But this kind of realization, also has certain limitation:

1, agreed to ctor as a constructor, new operation, actually called the ctor operation "can tolerate"

2, inheritance does not have a filter attribute, will inherit all the attributes of the parent class

3, the chain is too deep, will cause the sub-category over-bloated


Personally, the simpler items are completely unnecessary.

Only in the project, there is a strong succession relationship between the subordinate, it is the time when it glows heat.



JavaScript Inheritance Learning (i)

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.