依賴注入百科:https://baike.baidu.com/item/%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC/1158025javascript
假如如今有N多個類,須要用到Class B,那就須要在類裏面實例化N屢次,這樣對於後期的維護和管理都是不方便的,若是後期需求發生改變,那更改量有大不少。java
function A(){ } A.prototype.hello = function(){console.log("Hello, This is a")} function B(){ } B.prototype.talk = function(){ var a = new A(); a.hello() } //經過構造函數「注入「對象B1類 function B1(a){this.a = a} B1.prototype.talk = function(){ if(this.a){ this.a.hello(); } } var a1 = new A(); new B1(a1).talk(); function B2(){this.a =null} B2.prototype.setA = function(a){this.a = a} B2.prototype.talk = function(){ if(this.a){ this.a.hello(); } } var a2 = new A() var b2 = newB2(); b2.setA(a2); b2.talk();