Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn jQuery/Javascript functions into methods

Could anyone explain how to turn functions into methods and the variables into parameters of an object in jQuery/Javascript?

And even more interesting Why i should do that?

like image 809
gearsdigital Avatar asked Dec 30 '25 11:12

gearsdigital


1 Answers

There is (among others) the closure trick:

function obj(x, y) {
    var z = 0;

    return {
        foo: function() { z += x; return z; },
        bar: function() { z *= y; return z; }
    };
}

o = obj(2, 3);
o.foo();

This particular approach has the advantage that it hides internal state reasonably well. It is not easy (maybe impossible, but I'm not sure) to inadvertently tinker with z directly from outside the "object".

like image 161
Marcelo Cantos Avatar answered Jan 01 '26 00:01

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!