cocos-html5 JS 写法基础 语言核心

转载:http://blog.csdn.net/leasystu/article/details/18735797

cocos2dx 3.0 js继承:John Resiq的继承写法解析 CCClass.js 
cocos2d-html5/cocos2d/core/platform/CCClass.js

//创建一个function
cc.Class = function(){};
cc.Class.extend = function (prop) {
 //this为父类的对象
    var _super = this.prototype;
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
 //创建父类对象,这个prototype会被赋值给子类的原型
    var prototype = new this();
    initializing = false;
 //测试是否支持函数转字符串,正常情况 fnTest= /_super/
    fnTest = /xyz/.test(function(){xyz;}) ? /_super/ : /.*/;
 //prop子类创建对象的字面量
    // Copy the properties over onto the new prototype
    for (var name in prop) {
        // Check if we're overwriting an existing function
  //prop[name]就是名字为name的属性,或方法
        prototype[name] = typeof prop[name] == "function" &&
            typeof _super[name] == "function" && fnTest.test(prop[name]) ?
   //如果这个方法子类有,父类也有,而且子类在这个方法里面用了_super,就执行下面的语句
   /*
   首先执行一个匿名函数:传递方法名,(即:name),和子类的方法
   最后返回一个方法给原型中名字为name的方法(或者是说:给原型中添加一个名为name的方法)(语句0)
   */
   /*
   这个方法主要是进行了一层封装,当调用子类名为name的方法时,将调用这个返回的方法	这个方法主要是先给子类的_super方法指向为父类中名为name的方法(语句2    ),然后再真正的调用子类的方法(也就是这个fn)(语句3)	因为子类中的_super方法已经指向父类中名为name的方法,所以在调用fn时,如果这个fn里面用到   了_super,那么指向的就是父类的同名方法。
   然后在调用完之后,把子类中的_super重置(语句1 和 语句4)
            */
   (function (name, fn) {
                return function () {	//语句0
                    var tmp = this._super;	 //语句1
                    // Add a new ._super() method that is the same method
                    // but on the super-class
                    this._super = _super[name];	//语句2
                    // The method only need to be bound temporarily, so we
                    // remove it when we're done executing
                    var ret = fn.apply(this, arguments);	//语句3
                    this._super = tmp;	 //语句4
                    return ret;
                };
            })(name, prop[name]) :
            prop[name];
    }
 //创建子类,这个Class会覆盖外面的那个Class - -!
    // The dummy class constructor
    function Class() {
        // All construction is actually done in the init method
        if (!initializing) {
            if (!this.ctor)
                cc.log("No ctor function found, please set `classes_need_extend` section at `ini` file as `tools/tojs/cocos2dx.ini`");
            else
                this.ctor.apply(this, arguments);
        }
    }
 //给子类的原型赋值
    // Populate our constructed prototype object
    Class.prototype = prototype;
 //把子类原型中的构造函数指向自己
    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;
 //让子类也有extend方法
    // And make this class extendable
    Class.extend = arguments.callee;
    return Class;
};

---- 未完全理解。  留着慢慢品味...  

原文地址:https://www.cnblogs.com/porter/p/3777392.html