GWed
GWed

Reputation: 15673

How Can I Override A Function In Javascript

I have the following scripts:

<script ... jquery-1.9.1.js"></script>
<script ... dataTables.js"></script>    
<script ... columnFilter.js"></script>

The following code exists in columnFilter.js:

(function ($) {

   $.fn.columnFilter = function (options) {
       //some code...

       function _fnCreateCheckbox(oTable, aData) {
           //some code...
       }

   };

})(jQuery);

What I would like to do is override function _fnCreateCheckbox(oTable, aData) with my own code. Im fairly new to javascript, so would appreciate an example.

I have tried simply grabbing the code above and adding it to it's own <script> tags, but that didn't work. It completely stopped the columnFilter.js from working (which is as expected I guess). Not really sure what else to try.

Upvotes: 3

Views: 983

Answers (3)

Leeish
Leeish

Reputation: 5213

function _fnCreateCheckbox(oTable, aData) {

Only exists in the scope in which it was created as (function ($) { creates a function scope. You must edit it there. You can't override it outside the function.

EDIT: On a related note

If you are crafty with JS and you are trying to get that function to do something else only sometimes, you could pass some extra variables into your columnFilter plugin/function call and handle them in that function to do something else. I have no idea what column filter is, but let's pretend to call it on an element like so:

el.columnFilter({optionA: true, optionB: false});

If you wanted to do something else based on some data you have you could do,

el.columnFilter({optionA: true, optionB: false, extraOption: true});

Then in your script, depending on what your entire script does:

$.fn.columnFilter = function (options) {
   //some code...
   if(options.extraOption){
       function _fnCreateCheckbox(oTable, aData) {
           //some default code...
       }
   } else {
       function _fnCreateCheckbox(oTable, aData) {
           //my other code...
       }
   }
};

This is a crude example, but just to display your options.

Upvotes: 8

Malk
Malk

Reputation: 12003

You can override a function by reassigning its prototype. It is generally advised against though.

var d = new Date();

alert(d.getFullYear()); // 2013

Date.prototype.getFullYear = function() { return "Full Year"; }

alert(d.getFullYear()); // "Full Year"

http://jsfiddle.net/js5YS/

Upvotes: 1

alestanis
alestanis

Reputation: 21863

I suppose you import the columnFilter.js file from some external source.

One option could be to copy the columnFilter.js file to your project's directory, modify it as you please and then import it from your project's directory.

Upvotes: 2

Related Questions