xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

vanilla js overload function & override function All In One

vanilla js overload function & override function All In One

函数重载 overload

函数名相同,函数的参数不同(参数个数/参数类型/参数个数 &参数类型)

函数覆写(覆盖) override / rewriter

函数名相同,函数的参数相同(参数个数 &参数类型)

js 方法重写/ 方法重载

js 方法覆写

ts 方法重写/ 方法重载

ts 方法覆写

enhanced function, wrapped function, proxy function, logger function

    function rewriteHistory(type) {
        const origin = window.history[type];
        return function () {
            console.log(`arguments =`, arguments, this);
            console.log(`type =`, type, type.toLocaleLowerCase());
            const rs = origin.apply(this, arguments);
            // custom event
            const e = new Event(type.toLocaleLowerCase());
            e.arguments = arguments;
            // 手动触发事件 
            window.dispatchEvent(e);
            return rs;
        };
    }

🚀 在原来的方法上添加不存在的方法


    changeRouter (cb) {
        // rewrite function 🚀, why❓
        window.history.pushState = rewriteHistory('pushState');
        window.history.replaceState = rewriteHistory('replaceState');
        // popstate, 点击-浏览器的前进后退
        window.addEventListener('popstate', () => {
            this._emit(cb, '浏览器的前进后退 popstate');
        });
        // TODO: pushstate event ??? 不存在
        window.addEventListener('pushstate', () => {
            this._emit(cb, '❓单页路由变化 pushstate');
        });
        window.addEventListener('replacestate', () => {
            this._emit(cb, '❓单页路由替换 replacestate');
        });
        window.addEventListener('hashchange',(e) => {
            // console.log('hashchange event', e);
            const timeDiff = this._getTimestamp() - this.beginTimestamp;
            this.beginTimestamp = this._getTimestamp();
            console.log(`hashchange 待了时长: ${timeDiff}`);
            this._emit(cb, '单页路由 hashchange');
        });
    }

demos

https://cdn.xgqfrms.xyz/HTML5/history-api/pushstate-event.html

https://codepen.io/xgqfrms/pen/PobObbJ





rewirte pushstate & custom event

https://cdn.xgqfrms.xyz/HTML5/history-api/rewirte-pushstate-event.html

js multi events overwrite bug

https://cdn.xgqfrms.xyz/HTML5/history-api/url-change-event.html

    (function(history){
      var pushState = history.pushState;
      history.pushState = function(state) {
        // YOUR CUSTOM HOOK / FUNCTION
        log('called from pushStateHook', state, arguments);
        // func();
        return pushState.apply(history, arguments);
      };
    })(window.history);

ES5 Object.defineProperty

数据劫持


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

ES6 Proxy & Reflect


const target = {
  message1: "hello",
  message2: "everyone"
};

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy

https://javascript.info/proxy

TypeScript functions overloads

function overloading / method overloading

let suits = ["hearts", "spades", "clubs", "diamonds"];

function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x: any): any {
  // Check to see if we're working with an object/array
  // if so, they gave us the deck and we'll pick the card
  if (typeof x == "object") {
    let pickedCard = Math.floor(Math.random() * x.length);
    return pickedCard;
  }
  // Otherwise just let them pick the card
  else if (typeof x == "number") {
    let pickedSuit = Math.floor(x / 13);
    return { suit: suits[pickedSuit], card: x % 13 };
  }
}

let myDeck = [
  { suit: "diamonds", card: 2 },
  { suit: "spades", card: 10 },
  { suit: "hearts", card: 4 },
];

let pickedCard1 = myDeck[pickCard(myDeck)];
alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);

let pickedCard2 = pickCard(15);
alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);

https://www.typescriptlang.org/docs/handbook/functions.html#overloads

https://www.typescriptlang.org/docs/handbook/functions.html

https://www.tutorialsteacher.com/typescript/function-overloading

https://howtodoinjava.com/typescript/function-overloading/

https://stackoverflow.com/questions/13212625/typescript-function-overloading

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-02-23 20:03  xgqfrms  阅读(122)  评论(13编辑  收藏  举报