Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lgwebdream opened this issue Jul 6, 2020 · 5 comments
Labels
JavaScript teach_tag 新东方 company 编程题 teach_tag

Comments

@lgwebdream
Copy link
Owner

function A() {
  console.log("调用了函数A");
}
@lgwebdream lgwebdream added JavaScript teach_tag 新东方 company 编程题 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

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

@GolderBrother
Copy link

~(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
Copy link

```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
Copy link

m7yue commented Feb 20, 2021

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

const B = A;

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

A()

@juffyduan
Copy link

function wrapWidthA(A) {
  return function() {
    console.log('HelloWorld');
    return A.apply(this, arguments);
  }
}

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

const A = wrapWidthA(A);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 新东方 company 编程题 teach_tag
Projects
None yet
Development

No branches or pull requests

4 participants