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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With