<!DOCTYPE html> <html> <head> <meta content="width =device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="format-detection" content="telephone=no" /> <title></title> <style> html, body { margin: 0px; padding: 0px; height: 100%; width: 100%; } p { margin: 0px; padding: 0px; } .page { width: 100%; height: 100%; } </style> </head> <body> <script> //策略模式 //年終獎demo /* *根據績效發放 基本工資*月數=年終獎 */ /*-------------js面向對象模式--------------*/ //策略類 var performanceS = function () { };//績效S對象 performanceS.prototype.calculate = function (salary) { return salary * 4; } var performanceA = function () { }//績效A對象 performanceA.prototype.calculate = function (salary) { return salary * 3; } //環境類 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 () { return this.strategy.calculate(this.salary);//返回年終獎 } var bonus = new Bonus(); bonus.setSalary(1000); bonus.setStrategy(new performanceS()); console.log(bonus.getBonus()); /*-------------基於js--------------*/ //策略類 var strategies = { 'S': function (salary) { return salary * 4; }, 'A': function (salary) { return salary * 3; } } //環境類 var calculateBonus = function (level, salary) { return strategies[level](salary); } console.log(calculateBonus('S', 1000)); </script> </body> </html>