bsod99 bsod99 - 2 months ago 7
Javascript Question

Correct way to override this JavaScript class method

Apologies if this is quite an obvious, well documented one but I've not found much documentation which helps me with how I should best go about overriding a JavaScript class method when it has been set up as per below. In this snippet, if I want to override the _other method from another JS file, loaded after this one, what is the correct way to go about it? Thanks for any help.



var review = {};
"use strict";

(function ($) {

review.list = {

_init: function () {
// The code I want to leave intact
},

_other: function () {
// The code I want to override
},

init: function () {
$(document).ready(function () {
review.list._init();
review.list._other();
});
}
};

review.list.init();

})(jQuery);




Answer

You can just assign to review.list._other. If you want to have access to the previous version, grab that first:

var oldOther = review.list._other;
review.list._other = function() {
    // Your new code here, perhaps calling oldOther if you like
    console.log("The new other code ran.");
};

Example:

// The original file
var review = {};
"use strict";

(function($) {

  review.list = {

    _init: function() {
      // The code I want to leave intact
    },

    _other: function() {
      // The code I want to override
    },

    init: function() {
      $(document).ready(function() {
        review.list._init();
        review.list._other();
      });
    }
  };

  review.list.init();

})(jQuery);

// Your file after it
(function($) {
  var oldOther = review.list._other;
  review.list._other = function() {
    // Your new code here, perhaps calling oldOther if you like
    console.log("The new other code ran.");
  };

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You're actually quite lucky it was written that way. It could easily have been written such that you couldn't override _other at all...