JavaScript 组成工厂
示例
“优先于继承而不是继承”是一种重要且流行的编程原理,用于将行为分配给对象,而不是继承许多通常不需要的行为。
行为工厂
var speaker = function (state) { var noise =state.noise|| 'grunt'; return { speak: function () { console.log(state.name + ' says ' + noise); } }; }; var mover = function (state) { return { moveSlowly: function () { console.log(state.name + ' is moving slowly'); }, moveQuickly: function () { console.log(state.name + ' is moving quickly'); } }; };
对象工厂
var person = function (name, age) { var state = { name: name, age: age, noise: 'Hello' }; return Object.assign( //合并我们的“行为”对象 {}, speaker(state), mover(state) ); }; var rabbit = function (name, colour) { var state = { name: name, colour: colour }; return Object.assign( {}, mover(state) ); };
用法
var fred = person('Fred', 42); fred.speak(); //输出:Fred说你好 fred.moveSlowly(); //输出:Fred动作缓慢 var snowy = rabbit('Snowy', 'white'); snowy.moveSlowly(); //输出:Snowy移动缓慢 snowy.moveQuickly(); //输出:Snowy快速移动 snowy.speak(); //错误:snowy.speak不是函数