var performanceS=function(){};
performanceS.prototype.calculate=function(salary){
return salary*4;
}
var performanceA=function(){};
performanceA.prototype.calculate=function(salary){
return salary*3;
}
var performanceB=function(){};
performanceB.prototype.calculate=function(salary){
return salary*2;
}
var Bonus=function(){
this.salary=null;
this.strategy=null;
};
Bonus.prototype.setSalary=function(salary){
this.salary=salary;
}
Bonus.prototype.setStrategy=function(strategy){
this.strategy=strategy;
}
Bonus.prototype.getBonus=function(){
//这里的calculate是另外三个对象原型下的方法这为什么不报错,是怎么实现的
return this.strategy.calculate(this.salary);
}
var bonus=new Bonus();
bonus.setSalary(10000);
bonus.setStrategy(new performanceS());
console.log(bonus.getBonus());//40000
bonus.setStrategy(new performanceA());
console.log(bonus.getBonus());//30000
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
看代码:
为什么这里没报错,因为你 bonus.setStrategy(new performanceS());传入了performanceS的实例对象,
this.strategy的值就是performanceS的实例对象当然可以使用其原型下的calculate()方法,所以没报错。
涉及知识点原型链,函数创建的时候会自动创建的,自己找相关资料看看就知道怎么回事了