如果我想定义一个名字为MineViewController的JS类,代码如下:
defineClass("MineViewController:NJCSBaseViewController", { init:function(){ //doSomething }, viewWillAppear:function(){ //doSomething }, viewDidAppear:function(){ //doSomething }, viewWillDisappear:function(){ //doSomething }, viewDidDisappear:function(){ //doSomething }, dealloc:function(){ //doSomething } });上面代码就是定义了一个继承与NJCSBaseViewController且类名为MineViewController,实例方法有:init, viewWillAppear,viewDidAppear,viewWillDisappear,viewDidDisappear,dealloc; 这里重点介绍一下defineClass方法,源码如下:
// 类定义接口 function defineClass(declaration, instMethods, clsMethods) { var clsList = declaration.split(':'), clsName = clsList[0].trim(), superClsName = clsList[1] ? clsList[1].trim() : null; global[clsName] = global[superClsName].extend(instMethods); global[clsName].className = clsName; // 类方法处理 for (var methodName in clsMethods) { global[clsName][methodName] = clsMethods[methodName]; } }
defineClass方法有三个参数,逐一介绍:
declaration:要声明的类名和想继承的父类,字符串格式,如:”SubClass:SuperCLass”,冒号左边为要声明的类名字,冒号右边的时父类的名字;
instMethods:实例方法生命,字典格式,如:{init:function(){}, viewWillAppear:function(){},viewDidAppear:function(){}};
clsMethods:类方法声明,字典格式,如:{doSomething:function(){}, doSomethingTwo:function(){}};
有人可能会问,为什么没有属性的声明,因为属性可以在JS类内直接声明即可,如下:
defineClass("SubClass:SuperCLass",{init:function(){ this.instanceName = "";//实例属性instanceName this.id = "";//实例属性id }}, exampleFun:function(){ this.instanceName = "TestName";//对instanceName属性进行赋值 this.id = "110";//对id属性进行赋值 });