This article mainly introduces the methods for inheriting and instantiating JavaScript classes, and analyzes in detail the usage skills of javascript extension classes, instantiation classes, class objects and member functions, for more information about how to inherit and instantiate JavaScript classes, see the examples in this article. Share it with you for your reference. The details are as follows:
(Function () {var Class = {// extension class create: function (aBaseClass, aClassDefine) {var $ Class = function () {for (var member in aClassDefine) {this [member] = aClassDefine [member];} if ('undefined' = typeof aClassDefine. initialize) {this. initialize = function () {}}}; if ('function' === typeof aBaseClass) {$ class. prototype = new aBaseClass ();} else if ('object' === typeof aBaseClass) {$ class. prototype = aBaseClass;} return $ class;}, // instantiate class new: function (jclass, args) {var jclass = new jclass (); if (jclass. initialize) {jclass. initialize. apply (jclass, args) ;}return jclass ;}; // export window. class = Class ;})();
Example:
// Base class object or function var obj = {name: 'basename', init: function (){//...}, //...}; var fun = function () {this. name = ''; var init = function (){//...}; var getName = function () {return this. name ;}, var setName = function (name) {this. name = name; return this; // chain operation support },//...}; // inherit var class_frome_obj = Class from the Object. create (obj, {initialize: function () {// constructor}, getName: function () {return this. name ;}, setName: function (name) {this. name = name; return this; // chain operation support },//...}); // inherit var class_frome_fun = Class from the Function. create (fun, {initialize: function () {// constructor },//...}); // convert from null to the base Class var class_frome_base = Class. create ({}, {initialize: function () {// constructor },//...}); // instantiate var get_class_frome_obj = Class. new (class_frome_obj, [arg1, arg2,...]); var get_class_frome_fun = Class. new (class_frome_fun, [arg1, arg2,...]); var name1 = get_class_frome_obj.getName (); // console. log (name1); // BaseNamevar name2 = get_class_frome_obj.setName ('newname '). getName (); // console. log (name2); // NewName
I hope this article will help you design javascript programs.