Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override "private" function in JavaScript

I'm monkey-patching some of the jQuery's Draggable code*.

The goal is to avoid modifying the original source files and patch dynamically one of the internal functions.

The function _generatePosition is declared like this:

(function($) {

    $.widget("ui.draggable", $.ui.mouse, {
        ...
        _generatePosition: function(event) {
            ...
        }
    }
})(jQuery);

Is it possible to achieve the dynamic replacement of it?


*So it calculates the snapping grid relative to the top of parent element and not relative to the top of element being dragged. See here for more details.

like image 646
Art Avatar asked Aug 01 '10 13:08

Art


People also ask

Can we override private method in JavaScript?

You can't this way.

Can you override a private function?

No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.

Can we override private method in typescript?

Using protected is the correct way to solve this! But if you have no access to the parent class (e.g. because it is within a library) you also could overwrite private class member-function in the constructor.

Can we overload and override private method?

2) In Java, methods declared as private can never be overridden, they are in-fact bounded during compile time.


1 Answers

You can manipulate individual instances:

.draggable().data("draggable")._generatePosition = function() {};

Or modify the prototype, affecting all instances:

$.ui.draggable.prototype._generatePosition = function() {};
like image 86
Jörn Zaefferer Avatar answered Oct 02 '22 04:10

Jörn Zaefferer