先解释什么是依赖注入,依赖注入能解决什么问题
requirejs中的依赖注入
angular中反射方法的依赖注入
好处就是依赖的顺序可以打乱。
<!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 = {};
}
//获取一个函数的参数感觉toString这种写法很厉害啊,和arguments这种方式有什么区别?
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());//实际上这种方式还不是最佳的,应该是我根本无需关注这个key值。什么`pencil`,`notebook`,根本无需暴露
injector.resolve(student.write,student);
// student.write(new Pencil(),new Notebook());
</script>
</body>
</html>