先解釋什么是依賴注入踏志,依賴注入能解決什么問題
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>打開開發(fā)者工具胀瞪,在控制臺查看效果</p>
<script type="text/javascript">
var Injector = function(){
this._cache = {};
}
//獲取一個函數(shù)的參數(shù)感覺toString這種寫法很厲害啊针余,和arguments這種方式有什么區(qū)別?
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());//實際上這種方式還不是最佳的,應(yīng)該是我根本無需關(guān)注這個key值圆雁。什么`pencil`忍级,`notebook`,根本無需暴露
injector.resolve(student.write,student);
// student.write(new Pencil(),new Notebook());
</script>
</body>
</html>