I hope this article will help you learn how to use Simple Inheritance to create your own class instances.
I have been studying the writing of classes recently. Because some reusable and extensible methods are often used. I have been using components encapsulated by others before. It is more comfortable to use than Alare components developed by Yubo ~~
But not all projects need to use such complex components. If you use JQ to write one by yourself, JQ seems to have no class packaging yet, maybe in the future. After studying it for a long time, I found a good thing: Simple JavaScript Inheritance written by John Resig.
It is a perfect solution to my needs, and there are few codes. Below is a sample code I use.
The Code is as follows: |
Copy code |
(Function (){ /* * Simple Inheritance */ Var initializing = false; Var fnTest =/xyz/. test (function (){ Xyz; })? /B _superb /:/.*/; This. Class = function (){}; Class. extend = function (prop ){ Var _ super = this. prototype; Initializing = true; Var prototype = new this (); Initializing = false; For (var name in prop ){ Prototype [name] = typeof prop [name] = "function "&& Typeof _ super [name] = "function" & fnTest. test (prop [name])? (Function (name, fn ){ Return function (){ Var tmp = this. _ super; This. _ super = _ super [name]; Var ret = fn. apply (this, arguments ); This. _ super = tmp; Return ret; }; }) (Name, prop [name]): Prop [name]; }
Function Class (){ If (! Initializing & this. init) This. init. apply (this, arguments ); } Class. prototype = prototype; Class. constructor = Class; Class. extend = arguments. callee; Return Class; }; })();
$ (Function (){
// Define a Box class Var Box = Class. extend ({ Init: function (opts ){ Opts = $. extend ({ "Element": 'box' }, Opts | {}); This. opts = opts; This. element = $ (opts. element ); This. render (); }, Render: function (){ Var elEl = this. element; ElEl.html (this. opts. name + ',' + this. opts. age ); This. show (); }, Show: function (){ Var elEl = this. element; ElEl. show (); } });
// Instance 1-use new directly to instantiate the Box Var mybox = new Box ({ Element: '. mybox ', Name: 'zhang san ', Age: 15 });
// Instance 2-expand first, and then instantiate Box with new Var mybox2 = Box. extend ({ Init: function (opts ){ This. opts = opts; This. element = $ (opts. element ); This. render (); This. event (); }, Hide: function (){ Var elEl = this. element; ElEl. hide (); }, Event: function (){ Var elEl = this. element; Var that = this; ElEl. on ('click', function (){ That. hide (); }) } }); New mybox2 ({ Element: '. mybox2 ', Name: 'Li si ', Age: 55 });
}) |