复杂工厂模式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title></title> </head> <body> <script> //第一步 定义自行车的构造函数 两个属性 一个name和一个方法method var BicycleShop = function (name) { this.name = name this.method = function () { return this.name } } BicycleShop.prototype = { constructor: BicycleShop, /* * 买自行车这个方法 * @param {model} 自行车型号 */ sellBicycle: function (model) { var bicycle = this.createBicycle(model) // 执行A业务逻辑 bicycle.A() // 执行B业务逻辑 bicycle.B() return bicycle }, createBicycle: function (model) { throw new Error( '父类是抽象类不能直接调用,需要子类重写该方法' ) }, } // 实现原型继承 Sub表示子类,Sup表示超类 function extend(Sub, Sup) { // 首先定义一个空函数 var F = function () {} // 设置空函数的原型为超类的原型 F.prototype = Sup.prototype // 实例化空函数,并把超类原型引用传递给子类 Sub.prototype = new F() // 重置子类原型的构造器为子类自身 Sub.prototype.constructor = Sub // 在子类中保存超类的原型,避免子类与超类耦合 Sub.sup = Sup.prototype if ( Sup.prototype.constructor === Object.prototype.constructor ) { // 检测超类原型的构造器是否为原型自身 Sup.prototype.constructor = Sup } } var BicycleChild = function (name) { this.name = name // 继承构造函数父类中的属性和方法 BicycleShop.call(this, name) } // 子类继承父类原型方法 extend(BicycleChild, BicycleShop) // BicycleChild 子类重写父类的方法 BicycleChild.prototype.createBicycle = function () { var A = function () { console.log('执行A业务操作') } var B = function () { console.log('执行B业务操作') } return { A: A, B: B, } } var childClass = new BicycleChild('歌谣') console.log(childClass,"childClass") console.log(childClass.createBicycle())//a方法和b方法 console.log(childClass.sellBicycle())//执行a b业务操作 </script> </body> </html>
如何写一个简单的回调函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>如何写一个简单的回调函数</title> </head> <body> <script> //函数的参数为回调函数 function fangfang(callback) { var data = { "name": "fangyalan", "age": 18 }; callback(data); } //调用 fangfang(function (data) { //这里操作回调返回的数据 console.log(data) }) </script> </body> </html>