lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.83k stars 896 forks source link

有这样一个函数 A,要求在不改变原有函数 A 功能以及调用方式的情况下,使得每次调用该函数都能在控制台打印出“HelloWorld” #800

Open lgwebdream opened 4 years ago

lgwebdream commented 4 years ago
function A() {
  console.log("调用了函数A");
}
lgwebdream commented 4 years ago

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

GolderBrother commented 4 years ago
~(function(){
  Function.prototype.before = function(beforeFn){
    return (...args) => {
      // 先执行传入的beforeFn的函数
      beforeFn.apply(this, args);
      // 再执行调用beforeFn的函数
      const res = this.apply(this, args);
      return res;
    }
  }
  Function.prototype.after = function(afterFn){
    return (...args) => {
      // 先执行调用的after的函数
      const res = this.apply(this, args);
      // 再执行传入的afterFn函数
      afterFn.apply(this, args);
      return res;
    }
  }
  function A() {
    console.log("调用了函数A");
  }
  const fn = A.before(() => {
    console.log('before');
  }).after(() => {
    console.log('after');
  });
  fn();
})();
GolderBrother commented 4 years ago
```js
~(function(){
  Function.prototype.before = function(beforeFn){
    return (...args) => {
      // 先执行传入的beforeFn的函数
      beforeFn.apply(this, args);
      // 再执行调用beforeFn的函数
      const res = this.apply(this, args);
      return res;
    }
  }
  Function.prototype.after = function(afterFn){
    return (...args) => {
      // 先执行调用的after的函数
      const res = this.apply(this, args);
      // 再执行传入的afterFn函数
      afterFn.apply(this, args);
      return res;
    }
  }
  function A() {
    console.log("调用了函数A");
  }
  const fn = A.before(() => {
    console.log('before');
  }).after(() => {
    console.log('after');
  });
  fn();
})();
m7yue commented 3 years ago
function A() {
  console.log("调用了函数A");
}

const B = A;

A = () => {
  console.log('HelloWorld');
  B()
}

A()
juffyduan commented 10 months ago
function wrapWidthA(A) {
  return function() {
    console.log('HelloWorld');
    return A.apply(this, arguments);
  }
}

function A() {
  console.log("调用了函数A");
}

const A = wrapWidthA(A);