最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to add a callback function to an existing JavaScript function without adding code to the function? - Stack Overflow

programmeradmin1浏览0评论

Let say I have foo(). Is there a way to execute bar() after foo() without modifying foo()?

foo(){ /* logic */}

bar(){ /* more logic *}

afterEvent1AlwaysExecute2(foo,bar);

Any non-jQuery or jQuery ments are appreciated :)

Let say I have foo(). Is there a way to execute bar() after foo() without modifying foo()?

foo(){ /* logic */}

bar(){ /* more logic *}

afterEvent1AlwaysExecute2(foo,bar);

Any non-jQuery or jQuery ments are appreciated :)

Share Improve this question edited Nov 17, 2022 at 23:10 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 19, 2012 at 1:09 jdpubjdpub 312 bronze badges 1
  • You could always wrap foo inside a new function which will call the old foo, and then call bar. Then you change the name of this new function to foo. As far as the outside world is concerned foo should work as expected, but secretly your replaced implementation will also call bar. Win! – Anurag Commented Jul 19, 2012 at 1:14
Add a ment  | 

1 Answer 1

Reset to default 9

You can do it without adding code to foo, by reassigning the name foo:

var original_foo = foo;
var foo = function() { original_foo(); bar(); }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论