开发者

How to redefine JS function keeping previous in chain

This is common task coming from object oriented programming, I would like to change behavior of Jav开发者_StackOverflowaScript program by overriding existing function with possible calling it as well. I remember Windows introduced that as writing hooks and chaining them. So what I want, I have a web page which calls some onload hook which finally calls function initFields. I want to redefine this function however keep previous implementation. If I simply define my JS function as

function initFields() {
  // do some stuff ...
   // I do not know how to call super.initFields() here
}

I read something like you can write

initFields.prototype = function() {
     // do some stuff ...
     // but still have no idea how to call the original one
 };

Can somebody help?


One option is

var initFieldsInitial = initFields;
function initFields() {
   // your stuff
   initFieldsInitial.apply(this, arguments);
}


You could try the wrap() function from the underscore.js library.

http://documentcloud.github.com/underscore/#wrap

var initFields = function() {
    // do something
    console.log('initFields');
}

initFields = _.wrap(initFields, function(initial) {
    // do some stuff
    console.log('wrapper');
    initial();
});

$(document).ready(function() {
    initFields();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜