关键代码: [quote]var Injector = function(){ this._cache = {}; } Injector.prototype.getParamNames = function(func){ var paramNames = func.toString().match(/function\s+[^(](([^)]))/m)[1]; paramNames = paramNames.replace(/\s*/,""); paramNames = paramNames.split(","); return paramNames; } Injector.prototype.put = function(name,obj){ this._cache[name] = obj; } Injector.prototype.resolve = function(func,bind){ var paramNames = this.getParamNames(func),params = []; for(var i=0,l=paramNames.length;i<l;i++){ params.push(this._cache[paramNames[i]]); } func.apply(bind,params); }[/quote] 例子: html 代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <title>Injector Demo</title>
- <meta name="description" content="">
- <meta name="keywords" content="">
- <link href=""rel="stylesheet">
- </head>
- <body>
- <p > 打开开发者工具, 在控制台查看效果 </p>
- <script type="text/javascript">
- var Injector = function(){
- this._cache = {};
- }
- Injector.prototype.getParamNames = function(func){
- var paramNames = func.toString().match(/function\s+[^\(]*\(([^\)]*)\)/m)[1];
- paramNames = paramNames.replace(/\s*/,"");
- paramNames = paramNames.split(",");
- return paramNames;
- }
- Injector.prototype.put = function(name,obj){
- this._cache[name] = obj;
- }
- Injector.prototype.resolve = function(func,bind){
- var paramNames = this.getParamNames(func),params = [];
- for(var i=0,l=paramNames.length;i<l;i++){
- params.push(this._cache[paramNames[i]]);
- }
- func.apply(bind,params);
- }
- function Pencil(){}
- function Notebook(){}
- function Student(){}
- Student.prototype.write = function(pencil,notebook){
- if(!pencil || !notebook){
- throw new Error("lack of dependencies!!!");
- }else{
- console.log("use pencil to write something on notebook!");
- }
- }
- var injector = new Injector(),student = new Student();
- // 注入依赖
- injector.put("pencil",new Pencil());
- injector.put("notebook",new Notebook());
- injector.resolve(student.write,student);
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/17507/89d3d55d7cfc2009e89750adac120b82.html