zoukankan      html  css  js  c++  java
  • 【problem】更改原型对象的方法

    现有一个 Page 类, 其原型对象上有许多以 post 开头的方法 (如 postMsg); 另有一拦截函数 chekc, 只返回 ture 或 false. 请设计一个函数, 该函数应批量改造原 Page 的 postXXX 方法, 在保留其原有功能的同时, 为每个 postXXX 方法增加拦截验证功能, 当 chekc 返回 true 时继续执行原 postXXX 方法, 返回 false 时不再执行原 postXXX 方法

    function Page() {}
    
    Page.prototype = {
      constructor: Page,
    
      postA: function (a) {
        console.log('a:' + a);
      },
      postB: function (b) {
        console.log('b:' + b);
      },
      postC: function (c) {
        console.log('c:' + c);
      },
      check: function () {
        return Math.random() > 0.5;
      }
    }
    
    function checkfy(obj) {
      for (var key in obj) {
        if (key.indexOf('post') === 0 && typeof obj[key] === 'function') {
          (function (key) {
            var fn = obj[key];
            obj[key] = function () {
              if (obj.check()) {
                fn.apply(obj, arguments);
              }
            };
          }(key));
        }
      }
    } // end checkfy()
    
    checkfy(Page.prototype);
    
    var obj = new Page();
    
    obj.postA('checkfy');
    obj.postB('checkfy');
    obj.postC('checkfy');

    参考:GitHub

    我的理解:在 checkfy() 函数内部,因为 fn.apply() 调用,所以自调用的参数 key 才会接受 obj 的方法执行时的参数?

    也不是很理解原理。


  • 相关阅读:
    python matplotlib 绘图
    python set add 导致问题 TypeError: unhashable type: 'list'
    python 子类继承父类的__init__方法
    python 内存监控模块之memory_profiler
    git log 常用命令
    wireshark使用教程
    python os.path模块
    Linux crontab 定时任务
    linux环境变量LD_LIBRARY_PATH
    Linux的ldconfig和ldd用法
  • 原文地址:https://www.cnblogs.com/xiaochechang/p/5933510.html
Copyright © 2011-2022 走看看