PSport PSport - 3 months ago 10
jQuery Question

Call function in prototype from other prototype

I have two prototypes in my jquery script :

script1.prototype.initScript = function() {
//first one
this.saveGrid = function () {
alert("here");
}
};
script1.prototype.otherFunction = function () {
//second
//script1.initScript.saveGrid ?
};


I'd like to call
saveGrid
in
otherFunction
. How can I do that?

Edit :
And there ?

script1.prototype.initScript = function() {
//first one
this.saveGrid = function () {
alert("here");
}
};
script1.prototype.otherFunction = function () {
//second
$('button').on("click", function(){
//call savegrid here
});
};


Thanks.

Answer

You can access the function over this, like you already did in you example while creating the function saveGrid.

You should instead ask yourself, if this is a good idea, to create a function in another function and re-use them elsewere. What will happen, if you call otherFunction before initScript?

function script1() {}

script1.prototype.initScript = function() {
    this.saveGrid = function() {
        alert("here");
    }
};

script1.prototype.otherFunction = function() {
    this.saveGrid();
};

var s = new script1();
s.initScript();
s.otherFunction();

For you second example you have to store this before creating your event listener.

function script1() {}

script1.prototype.initScript = function() {
    this.saveGrid = function() {
        alert("here");
    }
};

script1.prototype.otherFunction = function() {
    var that = this;

    $('button').on("click", function(){
        that.saveGrid();
    });
};

var s = new script1();
s.initScript();
s.otherFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>

Comments