开发者

How to turn jQuery/Javascript functions into methods

Could anyone explain how to turn functio开发者_如何学编程ns 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".


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() { ... }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜