3

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?

1
  • 1
    thy "why should I do that" can be translated to "why use OOP" Commented Oct 23, 2010 at 9:09

2 Answers 2

3

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".

Sign up to request clarification or add additional context in comments.

Comments

3

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);

or with HJS plugin:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.