How to turn jQuery / Javascript functions into methods

Can someone explain how to turn functions into methods and variables into object parameters in jQuery / Javascript?

And even more interesting. Why should I do this?

+3
source share
2 answers

There is (among other things) a closing 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 of hiding the internal state well. It is not easy (perhaps impossible, but I'm not sure) to inadvertently mess with z directly from outside the "object".

+3
source

in jQuery:

var MyClass = function( x, y ) {
  this.x = x;
  this.y = y;
};
$.extend(MyClass.prototype, {
  foo: function(z) { ... },
  bar: function() { ... }
});

than you could:

var myObject = new MyClass(1, 2);

HJS:

var MyClass = $.Class.create({
  initialize: function(x, y) {
    this.x = x;
    this.y = y;
  }.
  foo: function(z) { ... },
  bar: function() { ... }
});
+3

Source: https://habr.com/ru/post/1771052/


All Articles