JavaScript依赖注入 [英] JavaScript Dependency Injection

查看:136
本文介绍了JavaScript依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的JavaScript。我不知道如何在JavaScript中实现依赖注入?我搜索了互联网,但找不到任何东西。

解决方案

  var Injector = {
依赖关系:{},
add:function(qualifier,obj){
this.dependencies [qualifier] = obj;
},
get:function(func){
var obj = new func;
var dependencies = this.resolveDependencies(func);
func.apply(obj,dependencies);
return obj;
},
resolveDependencies:function(func){
var args = this.getArguments(func);
var dependencies = [];
for(var i = 0; i< args.length; i ++){
dependencies.push(this.dependencies [args [i]]);
}
返回依赖关系;
},
getArguments:function(func){
//这个正则表达式来自require.js
var FN_ARGS = / ^ function\s * [^ \ * \(\s *([^ \)] *)\)/ M;
var args = func.toString()。match(FN_ARGS)[1] .split(',');
return args;
}
};

我们需要一个配置来提供必要的限定符依赖关系的第一件事。为此,我们将依赖项定义为Injector类中的依赖关系。我们使用依赖关系集作为我们的容器,它将处理映射到限定符的对象实例。为了添加具有限定符的依赖关系集的新实例,我们定义一个add方法。之后,我们定义get方法来检索我们的实例。在这种方法中,我们首先找到arguments数组,然后将这些参数映射到依赖关系。之后,我们只是使用依赖关系构造对象并返回它。有关详细信息和示例,请参阅我博客上的发布


I am new at JavaScript. I wonder how dependency injection is being implemented in JavaScript? I searched the internet but couldn't find anything.

解决方案

var Injector = {
   dependencies: {},
   add : function(qualifier, obj){
      this.dependencies[qualifier] = obj; 
   },
   get : function(func){
      var obj = new func;
      var dependencies = this.resolveDependencies(func);
      func.apply(obj, dependencies);
      return obj;
   },
   resolveDependencies : function(func) {
      var args = this.getArguments(func);
      var dependencies = [];
      for ( var i = 0; i < args.length; i++) {
         dependencies.push(this.dependencies[args[i]]);
      }
      return dependencies;
   },
   getArguments : function(func) {
      //This regex is from require.js
      var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
      var args = func.toString().match(FN_ARGS)[1].split(',');
      return args;
   }
};

The first thing we need a configuration to provide necessary dependencies with qualifiers. To do that, we define a dependency set as dependencies in the Injector class. We use dependency set as our container which will take care of our object instances mapped to qualifiers. In order to add new instance with a qualifier to dependency set, we define an add method. Following that, we define get method to retrieve our instance. In this method, we first find the arguments array and then map those arguments to dependencies. After that, we just construct the object with our dependencies and return it. For more information and examples, please see the post on my blog.

这篇关于JavaScript依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆