主页 > 前端 > javascript >
来源:未知 时间:2015-07-25 19:57 作者:xxadmin 阅读:次
[导读] 本文讲解JavaScript类继承及实例化的方法 (function(){varClass={//扩展类create:function(aBaseClass,aClassDefine){var$class=function(){for(varmemberinaClassDefine){this[member]=aClassDefine[member];}if(undefined===typeofaClassD...
本文讲解JavaScript类继承及实例化的方法 (function(){ var 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; }, //实例化类 new: function(jclass,args){ var jclass = new jclass(); if(jclass.initialize){ jclass.initialize.apply(jclass, args); } return jclass; } }; //export window.Class = Class; })(); 示例: //基类对象或函数 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;//链式操作支持 }, //... }; //从Object继承 var class_frome_obj = Class.create(obj,{ initialize: function(){ //构造函数 }, getName: function(){ return this.name; }, setName: function(name){ this.name = name; return this;//链式操作支持 }, //... }); //从Function继承 var class_frome_fun = Class.create(fun,{ initialize: function(){ //构造函数 }, //... }); //从空对生成基类 var class_frome_base = Class.create({},{ initialize: function(){ //构造函数 }, //... }); //实例化 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);//BaseName var name2 = get_class_frome_obj.setName('NewName').getName(); //console.log(name2);//NewName |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com