`
openxtiger
  • 浏览: 151757 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

[原创]类似Java语法的Javascript框架js5,实现jpackage,jimport,jextends,jclass,jnew

阅读更多

终于到java的关键字package,import,extends,class,new实现了一遍。

代码为证:

 

 

var Js5 = {version:"5.0.0"};
var __cpackage__;
var __gclasses__ = {};
var __iclasses__ = {};
var __imports__ = [];

Js5.apply = function(o, c) {
    if (o && c && typeof c == 'object') {
        for (var p in c) {
            o[p] = c[p];
        }
    }
    return o;
};

(function() {
    var toString = Object.prototype.toString,
        oc = Object.prototype.constructor;

    Js5.apply(Js5, {
        applyIf : function(o, c) {
            if (o) {
                for (var p in c) {
                    if (!Js5.isDefined(o[p])) {
                        o[p] = c[p];
                    }
                }
            }
            return o;
        },
        override: function(origclass, overrides) {
            if (overrides) {
                var p = origclass.prototype;
                Js5.apply(p, overrides);
            }
        },
        /*override : function(origclass, overrides) {
         if (overrides) {
         var p = origclass.prototype;
         overrides = overrides(p.superclass);

         Js5.apply(p, overrides);

         if (Js5.isIE && overrides.hasOwnProperty('toString')) {
         p.toString = overrides.toString;
         }
         }

         },*/
        isFunction : function(v) {
            return toString.apply(v) === '[object Function]';
        },
        isString : function(v) {
            return typeof v === 'string';
        },
        isBoolean : function(v) {
            return typeof v === 'boolean';
        },
        isElement : function(v) {
            return !!v && v.tagName;
        },
        isDefined : function(v) {
            return typeof v !== 'undefined';
        },
        isObject : function(v) {
            return !!v && Object.prototype.toString.call(v) === '[object Object]';
        },
        isDate : function(v) {
            return toString.apply(v) === '[object Date]';
        },
        isPrimitive : function(v) {
            return Js5.isString(v) || Js5.isNumber(v) || Js5.isBoolean(v);
        },
        isNumber : function(v) {
            return typeof v === 'number' && isFinite(v);
        },
        isEmpty : function(v, allowBlank) {
            return v === null || v === undefined || ((Js5.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false);
        },
        isArray : function(v) {
            return toString.apply(v) === '[object Array]';
        },
        isIterable : function(v) {
            //check for array or arguments
            if (Js5.isArray(v) || v.callee) {
                return true;
            }
            //check for node list type
            if (/NodeList|HTMLCollection/.test(toString.call(v))) {
                return true;
            }
            //NodeList has an item and length property
            //IXMLDOMNodeList has nextNode method, needs to be checked first.
            return ((typeof v.nextNode != 'undefined' || v.item) && Js5.isNumber(v.length));
        },
        each : function(array, fn, scope) {
            if (Js5.isEmpty(array, true)) {
                return [];
            }
            if (!Js5.isIterable(array) || Js5.isPrimitive(array)) {
                array = [array];
            }
            for (var i = 0, len = array.length; i < len; i++) {
                if (fn.call(scope || array[i], array[i], i, array) === false) {
                    return i;
                }
            }
            return [];
        },
        namespace : function() {
            var o, d;
            Js5.each(arguments, function(v) {
                d = v.split(".");
                o = window[d[0]] = window[d[0]] || {};
                Js5.each(d.slice(1), function(v2) {
                    o = o[v2] = o[v2] || {};
                });
            });
            return o;
        },
        nameclass:function(c) {
            if (__gclasses__[c]) return __gclasses__[c];
            var d = c.split(".");
            var o = window[d[0]] = window[d[0]] || {};
            Js5.each(d.slice(1, d.length - 1), function(v2) {
                o = o[v2] = o[v2] || {};
            });
            return __gclasses__[c] = o[d[d.length - 1]];
        },
        importclass:function(c) {
            if (__gclasses__[c]) return __gclasses__[c];
            if (__iclasses__[c]) return __iclasses__[c];

            var d = c.split(".");
            var o = window[d[0]] = window[d[0]] || {};
            var name = d[d.length - 1];
            Js5.each(d.slice(1, d.length - 1), function(v2) {
                o = o[v2] = o[v2] || {};
            });
            if (o[name]) {
                o = __gclasses__[c] = o[name];
            } else {
                Js5.each(__imports__, function(i) {
                    if ((o = i[name])) {
                        return false;
                    }
                });

                __iclasses__[c] = o;
            }

            return o;
        }
    });
})();


/**
 * p1:String ==>package name
 * p2..p-1,Object ==>imports
 * p-1,function ==> package body
 */
function jpackage() {
    var l = arguments.length,i = 0;
    if (l == 0) return;
    var pkf = arguments[l - 1];
    pkf.$Define = true;

    if (Js5.isString(arguments[0])) {
        __cpackage__ = Js5.namespace(arguments[0]);
        i = 1;
    } else {
        __cpackage__ = window;
        i = 0;
    }
    var args = [],vs,ip;
    Js5.each(Array.prototype.slice.call(arguments, i, l - 1), function(v) {
        if (Js5.isString(v)) {
            vs = v.split(";");
            Js5.each(vs, function(v2) {
                if (v2.substr(-2) == ".*") {
                    ip = Js5.namespace(v2.substring(0, v2.length - 2));
                    __imports__.push(ip);
                    args.push(ip);
                } else {
                    args.push(Js5.importclass(v2));
                }
            });
        } else if (Js5.isArray(v)) {
            args = args.concat(v);
        } else {
            args.push(v);
        }
    });
    pkf.apply(__cpackage__, args);

    __cpackage__ = null;
    __imports__ = [];
    __iclasses__ = {};

}

function jimport() {
    var args = [],vs,ip;
    __imports__ = [];
    __iclasses__ = {};
    if (jimport.caller) {
        jimport.caller.$Define = true;
    }
    Js5.each(arguments, function(v) {
        if (Js5.isString(v)) {
            vs = v.split(";");
            Js5.each(vs, function(v2) {
                if (v2.substr(-2) == ".*") {
                    ip = Js5.namespace(v2.substring(0, v2.length - 2));
                    __imports__.push(ip);
                    args.push(ip);
                } else {
                    args.push(Js5.importclass(v2));
                }
            });
        } else if (Js5.isArray(v)) {
            args = args.concat(v);
        } else {
            args.push(v);
        }
    });
    return args;
}

function jextends() {

    var oc = Object.prototype.constructor;
    var l = arguments.length;
    var sb = arguments[0];
    var sp = arguments[1];
    var mixins = [];
    var coverrides;
    if (l < 2) {
        throw new Error("[jextends] invalid arguments");
    }
    if (l == 2) {
        coverrides = sp;
        sp = sb;
    } else if (Js5.isArray(arguments[2])) {
        mixins = arguments[2];
        coverrides = sp;
        sp = sb;
        l = 2;
    } else {
        coverrides = arguments[2];
        if (l == 4) {
            mixins = arguments[3];
        }
    }
    if (Js5.isString(sp)) {
        sp = Js5.importclass(sp);
    }

    var E = function() {
    },sbp,spp = sp.prototype;
    E.prototype = spp;

    mixins.unshift(spp);

    if (Js5.isFunction(coverrides)) {
        coverrides.$Define = true;
        coverrides = coverrides.apply(this, mixins);
    }

    if (l == 2) {
        sb = coverrides.constructor != oc ? coverrides.constructor : function() {
            sp.apply(this, arguments);
        };
    }
    sbp = sb.prototype = new E();
    sbp.constructor = sb;
    sb.superclass = spp;
    if (spp.constructor == oc) {
        spp.constructor = sp;
    }

    /*sbp.superclass = (function() {
     return spp;
     });*/

    Js5.override(sb, coverrides);  // extend coverrides

    if (mixins.length > 1) {
        for (var i = 1,len = mixins.length; i < len; i++) {
            Js5.applyIf(sbp, mixins[i]);
        }
    }

    return sb;
}

/**
 * p1:String ==>class name
 * p2,String ==>same package;Object
 * p3,function ==>
 */
function jclass() {
    var l = arguments.length,i = 0;
    if (l == 0) {
        throw new Error("[jclass] invalid arguments");
    }
    if (!Js5.isString(arguments[0])) {
        throw new Error("[jclass] class name must be string");
    }
    if (l == 1) {
        return jclass.caller && jclass.caller.$Define ? __cpackage__ && __cpackage__[name] ||
            Js5.importclass(arguments[0]) : Js5.nameclass(arguments[0]);
    }

    var clf = arguments[l - 1];


    var p;
    if (l >= 3) {
        var name = arguments[1];
        if (Js5.isString(name)) {
            p = __cpackage__ && __cpackage__[name] || Js5.importclass(name);
        } else {
            p = arguments[1];
        }
    } else {
        p = Object;
    }
    if (!p) {
        throw new Error("[jclass] unrecognized parent class");
    }
    var mixins = [];

    if (l >= 4) {
        var vs;
        var mc;
        Js5.each(Array.prototype.slice.call(arguments, 2, l - 1), function(v) {
            if (Js5.isString(v)) {
                vs = v.split(",");
                Js5.each(vs, function(v2) {
                    mc = Js5.importclass(v2);
                    if (mc) {
                        mixins.push(mc.prototype);
                    }

                });

            } else {
                mixins.push(v.prototype);
            }
        });
    }

    var cls = jextends(p, clf, mixins);

    if (arguments[0]) {
        __cpackage__[arguments[0]] = cls;
    }

    return cls;
}

function jnew() {
    var l = arguments.length,i = 0;
    if (l == 0) return {};

    var args = Array.prototype.slice.call(arguments, 1);

    var name = arguments[0];

    var cls;
    if (Js5.isString(name)) {
        cls = jnew.caller && jnew.caller.$Define ?
            __cpackage__ && __cpackage__[name]
                || Js5.importclass(name) : Js5.nameclass(name);

        if (!cls) {
            throw new Error("[jnew] unrecognized class,use whole class name");
        }
    } else {
        cls = name;
    }


    /*var temp = function() {
     };

     var constructor = cls.prototype.constructor;
     var instanceCls = function() {
     return constructor.apply(this, args);
     };

     temp.prototype = cls.prototype;
     instanceCls.prototype = new temp();
     instanceCls.prototype.constructor = instanceCls;

     return new instanceCls();*/

    var obj = {};
    Js5.override(obj, cls);
    obj.__proto__ = cls.prototype;
    cls.apply(obj, args);
    return obj;
}

function jsupercall(cls, method, args) {
    var sp = Js5.isString(cls) ? jsupercall.caller && jsupercall.caller.$Define ? Js5.importclass(cls) : Js5.nameclass(cls) : cls;
    return sp.superclass[method].apply(this, args);
}

 

 

 

还有例子:

 

 

  var jui = {};

  jpackage("jui", function() {

    jclass("Component", function() {
      return {
        constructor:function(x) {
          console.log("Component:" + x);
        },
        show:function() {
          console.log("Component");
        }
      }
    });

    jclass("Container", "Component", function(_supr) {
      return {
        constructor:function(x) {
          console.log("Container:" + x);
          _supr.constructor.call(this, x);
        }
      };
    });

  });

  jpackage("jui", function() {

    jclass("Window", "Container", function(_supr) {
      return {
        show:function() {
          console.log("Window");
        }
      }
    });

  });

  jpackage("jui.form", function() {

    jimport("jui.*");

    jclass("TextField", "Component", function(_supr) {
      return {
        show:function() {
          console.log("TextField");
        }
      }
    });


  });

  jpackage("js5.util", function() {

    jclass("Observable", function(_supr) {
      return {
        constructor:function() {
          console.log("Observable.constructor");
        },
        on:function() {
          console.log("Observable.on");
        },
        show:function() {
          console.log("Observable.show");
        }
      }
    });

  });

  jpackage("jui.ex", jimport("jui.Window;jui.*;jui.form.*"), function(_W, j) {

    jclass("Window", "jui.Window", "js5.util.Observable", function(_supr, _ob) {
      return {
        constructor:function(x) {
          console.log("jui.ex.Window.constructor");
          _supr.constructor.call(this, x);
          _ob.constructor.call(this);
        },
        show:function() {
          console.log("Window Ex");
          _supr.show();
        }
      }
    });

    var MyWindow = jclass("", "jui.Window", function() {

      return {
        show:function() {
          console.log("anonymous myWindow");
        }
      }
    });


    var x = jnew("Window", "package jui.ex.Window");
    x.show();
    x.on();

    x = new MyWindow("ssssssss");
    x.show();

    jclass("jui.Window").superclass.constructor.call(this, "111111111111");


    x = jnew(jui.Window, "jui.Window : new in package, use complete class path");
    x.show();

    x = new jui.Window("jui.Window : new in package, use complete class path");
    x.show();

    x = jnew("jui.Window", "jui.Window: new in package, use complete class path");
    x.show();

    x = new j["Window"]("jui.Window: new in package, use import jui.*");
    x.show();

    x = new _W("jui.Window:  new in package, use import jui.Window");
    x.show();

    for (var i = 1; i <= 5; i++) {
      x = jnew("TextField", "jui.form.TextField  new in package,use import jui.form.*");
      x.show();
    }


  });

  var a = jextends(jui.Window, function() {
   return {
   show:function() {
   console.log("jextends show");
   }
   }
   });


  var x = jnew("jui.ex.Window", "global jui.ex.Window");
  x.show();
 

 

 

1
1
分享到:
评论
6 楼 openxtiger 2012-11-17  
加了一个更加像Java定义的方法:jjava

function jjava(def, code) {
    var defs = def.replace(/\s{2}/g, '').split(/\s/);
    var l = defs.length;
    if (l % 2 != 0) {
        throw new Error("[jjava] def error");
    }
    var args = [];
    for (var i = 0; i < l; i += 2) {
        switch (defs[i]) {
            case "class":
                args[0] = defs[i + 1];
                break;
            case "extends":
                args[1] = defs[i + 1];
                break;
            case "implements":
                args = args.concat(defs[i + 1].replace(/\s/).split(","));
                break;
        }
    }
    args.push(code);

    return jclass.apply(this, args);

}


例子:
jjava('class Container extends Component implements ', function(jsuper) {

        return {

            constructor:function() {
                jsuper.constructor.call(this);
            }


        }

    });
5 楼 hoodng 2012-11-12  
openxtiger 写道
还有,这个作法,并没有把定义和运行分开,所以每次创建对象时,将又重新定义了对象。


如果你仔细阅读我的例子,你会发现,定义和运行是完全分开的,仅有第一次new 对象时,定义才被执行。
4 楼 hoodng 2012-11-12  
openxtiger 写道
这种写法的确是一个很大创新,可以这样是破坏了面向对象的模式,看起来像面相函数。还有继承和函数的重载会有很多bug!


   实际上刚好相反,我给你的这个例子,可以完全理解成一个Button类 (just like java.awt.Button), 它不会破坏面向对象的模式,因为它几乎和Java一样。
  
   至于继承和重载是我的J$VM的框架的能力,我想你仅从上面给得例子得出bug很多,有点绝对了。
3 楼 openxtiger 2012-11-07  
还有,这个作法,并没有把定义和运行分开,所以每次创建对象时,将又重新定义了对象。
2 楼 openxtiger 2012-11-07  
这种写法的确是一个很大创新,可以这样是破坏了面向对象的模式,看起来像面相函数。还有继承和函数的重载会有很多bug!
1 楼 hoodng 2012-11-02  
让Java程序员来看上面的代码,感觉还是太陌生。jpackage, jimport都以非常奇怪的形式出现。

如果是下面这种语法,就真正是Java like了。即便是C/C++程序员也能很快上手。

$package("js.awt"); // Define js.awt package

$import("js.awt.Component"); // Import js.awt.Component

/**
 * Define Button component
 * 
 * @param def:{
 *   className: string, required
 * 
 *   id: request,
 *   
 *   iconImage: "",
 *   iconAlign: "left"|"right"|"top"|"bottom" 
 *   labelText: "Button",   
 * 
 *   state:optional,
 *   toggle:boolean, required
 * 
 * }
 */
js.awt.Button = function(def, Runtime){

    var CLASS = js.awt.Button, thi$ = CLASS.prototype;
    if(CLASS.__defined__){
        this._init.apply(this, arguments);
        return;
    }
    CLASS.__defined__ = true;

    var Class = js.lang.Class, Event = js.util.Event, DOM = J$VM.DOM,
    System = J$VM.System;
    
    thi$.setIconImage = function(state){
        // TODO: 
    };

    thi$.getIconImage = function(){
        // TODO: 
    };
    
    thi$.setText = function(text){
        // TODO: 
    };
    
    thi$.getText = function(){
        // TODO: 
    };

    thi$.setToolTipText = function(s){
        // TODO: 
    }.$override(this.setToolTipText);


    var _onmousedown = function(e){
        // TODO: 
    };

    var _onmouseup = function(e){
        // TODO: 
    };

    var _onmouseover = function(e){
        // TODO: 
    };

    var _onmouseout = function(e){
        // TODO: 
    };

    thi$.destroy = function(){
        // TODO ...        
        arguments.callee.__super__.apply(this, arguments);

    }.$override(this.destroy);
    
    thi$._init = function(def, Runtime, view){
        if(typeof def !== "object") return;
        
        def.classType = def.classType || "js.awt.Button";
        def.className = def.className || "jsvm_button";

        arguments.callee.__super__.apply(this, [def, Runtime, view]);
        
        // TODO .....

        this.attachEvent("mouseover", 0, this, _onmouseover);
        this.attachEvent("mouseout",  0, this, _onmouseout);
        this.attachEvent("mousedown", 0, this, _onmousedown);
        this.attachEvent("mouseup",   0, this, _onmouseup);

    }.$override(this._init);

    this._init.apply(this, arguments);
    
}.$extend(js.awt.Component);


相关推荐

    jimport_038.zip

    标题 "jimport_038.zip" 暗示了这是一个与Java和Delphi相关的软件或工具包。这个压缩文件可能包含了一种工具,允许用户在Delphi开发环境中导入或使用Java代码。让我们深入探讨一下这个主题。 首先,Delphi是...

    jimport_039.zip

    标题“jimport_039.zip”提示我们这是一个与Java和可能的代码导入相关的压缩文件。结合描述,我们可以推测这可能是一个工具或库,用于在Delphi开发环境中整合或使用Java代码。标签“Delphi”进一步确认了这一点,...

    joomla模板开发教程

    2. **添加 JavaScript**:虽然在这个例子中没有直接添加 JS 文件,但通常你可以使用类似的方法 (`$doc-&gt;addScript()`) 来引入 JavaScript 文件,或者使用 `JHtml::_('behavior.framework', true);` 这样的语句来启用...

    Joomla.HTML 核心链接库讲解文档

    - 示例:与基本类型 Image 类似,但可能包含更多的功能。 #### 五、实战应用 了解了 Joomla.HTML 链接库的基本类型和组类型后,我们来看几个实战应用的例子: 1. **创建一个链接** ```php echo JHTML::_('link'...

    joomla调试工具

    在你的代码中,你可以通过调用`jimport('joomla.debug.dump')`来引入`j!dump`函数,然后像使用`var_dump()`一样,将需要检查的变量作为参数传递给`j!dump()`。例如: ```php $variable = array(...); jimport...

    kettle-neo4j-cypher-output:使用带有参数的Cypher将数据输出到Neo4j

    "Java" 标签表明该插件是用Java语言实现的,这使得它能够跨平台运行,并且可以利用Java丰富的库和API来与Neo4j进行交互。 在Kettle中使用"带有参数的Cypher将数据输出到Neo4j"意味着用户可以在Cypher查询中动态地...

    Joomla下利用configuration.php存储简单数据

    这可以通过调用`JFactory::getCache()`获取缓存实例,然后调用`clean()`方法实现。 3. **更新配置值**:接下来,使用`JFactory::getConfig()`获取配置对象的引用,并调用`setValue()`方法来设置新的配置项。例如,...

Global site tag (gtag.js) - Google Analytics