原型 —> 继承

image.png

  1. function Teacher(){
  2. this.name = 'Mr.Li';
  3. this.tSkill = 'JAVA';
  4. }
  5. Teacher.prototype = {
  6. pSkill: 'JS'
  7. }
  8. var t = new Teacher();
  9. console.log(t);
  10. function Student(){
  11. this.name = 'Mr.Wang';
  12. }
  13. // 中间件-缓冲
  14. function Buffer(){}
  15. Buffer.prototype = Teacher.prototype; // 继承了Teacher的原型
  16. var buffer = new Buffer();
  17. Student.prototype = buffer;
  18. Student.prototype.age = 18; // 修改Student原型不影响Teacher的原型
  19. var s = new Student();
  20. console.log(s);
  21. // 继承和隔离
  22. 修改Student原型不影响Teacher的原型
  23. // 圣杯模式
  24. function Teacher(){}
  25. function Student(){}
  26. function Buffer(){}
  27. //Buffer.prototype = Teacher.prototype;
  28. //var buffer = new Buffer();
  29. //Student.prototype = buffer;
  30. inherit(Student, Teacher);
  31. var s = new Student();
  32. var t = new Teacher();
  33. 封装
  34. function inherit(Target, Origin){
  35. function Buffer(){}
  36. Buffer.prototype = Origin.prototype;
  37. Target.prototype = new Buffer();
  38. Target.prototype.constructor = Target; // 将构造器指回本身 还原构造器
  39. Target.prototype.super_class = Origin; // 继承源
  40. }

image.png
圣杯布局模式

闭包

  1. 函数形式

image.png

  1. 对象形式

image.png

  1. 构造函数形成闭包 ```typescript function Compute(){ var num = 0;

    this.add = function(){ num++; console.log(num); }

    this.minus = function(){ num—; console.log(num); } // var compute = {} 对象形式 return compute // vat this = {} new生成this,然后隐式return this // return this; // reutrn 123;无效,忽略 return {} 引用值就不会return this }

var compute = new Compute(); compute.add();

  1. 4. 圣杯模式-闭包
  2. ```typescript
  3. var inherit = (function(){
  4. var Buffer = function(){} //Buffer内部属性,不会污染全局
  5. return function inherit(Target, Origin){
  6. Buffer.prototype = Ofigin.prototype;
  7. Target.prototype = new Buffer();
  8. Target.prototype.constructor = Target; // 将构造器指回本身 还原构造器
  9. Target.prototype.super_class = Origin; // 继承源
  10. }
  11. })(); // 自执行
  12. inherit(Student,Teacher);
  13. // 防止变量全局污染
  14. // 模块化开发

封装

  1. var initCompute = (function(){
  2. var a=1,b=2;
  3. function add(){
  4. console.log(a+b);
  5. }
  6. function minus(){
  7. console.log(a-b);
  8. }
  9. function mul(){
  10. console.log(a*b);
  11. }
  12. function div(){
  13. console.log(a/b);
  14. }
  15. return function(){
  16. add();
  17. minus();
  18. mul();
  19. div();
  20. }
  21. })();
  22. var initFunctions = (function(){})();
  23. function init(){
  24. initCompute();
  25. initFunctions();
  26. }
  27. window.onload = function(){
  28. init();
  29. }
  1. 插件化
  2. // 自启动
  3. ;(function(){
  4. var Slider = function(opt){}
  5. Slider.prototype = {}
  6. window.Slider = Slider;
  7. })();
  8. var slider = new Slider({})
  9. // 手动执行
  10. var Test = (function(){
  11. var Test = function(){}
  12. Test.prototype={}
  13. return Test;
  14. })();

image.png
立即执行函数执行后返回fb保存在initFb(全局变量)中,然后该执行函数销毁,调用initFb即调用fb