我们知道调用类需要实例化它 生成一个对象 我们常常写一个类需要调用其他类 也许其他类也调用(依赖)其他类 这样得实例化多少次
var a = new A() ;
a.ob = new B() ;
a.oc = new C() ; 这样看起来代码太恶心了 所有就有了依赖注入
依赖注入全称叫“依赖注入到容器(IOC)” 你可以把所有依赖关系的类(不管有多少类)注入到该容器 然后解析实例化该类
function PetKeeper(pet) {
this.pet = pet ;
}
PetKeeper.prototype.feed = function(food) {
this.pet.eat(food) ;
}
function Pet(type) {
this.type = type ;
}
Pet.prototype.eat = function(food) {
console.log("I am a " + this.type +",I am eating" + " food")
}
var cat = new Pet("cat") ;
var keeper = new PetKeeper(cat) ;
cat.eat("fish") ;//I am a cat,I am eating food
keeper.feed("fish") ;//I am a cat,I am eating food