javascript 依賴注入程式碼例項

antzone發表於2017-04-13

關於什麼依賴注入,大家可以自行在網上查詢。

下面分享一個使用javascript實現的依賴注入程式碼例項。

程式碼如下:

[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);

相關文章